Java异常处理编程:捕获和重写
在Java中,异常处理是一种机制,用于在程序运行过程中遇到错误时进行处理。主要的异常处理流程包括抛出异常、捕获异常以及重写异常。
- 抛出异常:
当代码执行过程中出现问题时,可以使用throw
关键字抛出一个异常对象。例如:
public class Example {
public void divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
//... further code
}
public static void main(String[] args) {
Example example = new Example();
try {
example.divide(10, 0);
} catch (IllegalArgumentException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
- 捕获异常:
当一个方法或代码块可能抛出特定异常时,可以在这些地方使用try-catch
结构来捕获异常。例如:
public class Example {
public void divide(int a, int b) throws IllegalArgumentException {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
//... further code
}
public static void main(String[] args) {
Example example = new Example();
try {
example.divide(10, 0);
} catch (IllegalArgumentException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
- 重写异常:
如果你想要处理特定的异常,但不想完全捕获它,而是希望以某种方式改变或重新抛出这个异常。你可以使用throws
关键字在方法声明中指定可能抛出的异常,并在该方法内部重写这些异常。
例如:
public class Example {
public void divide(int a, int b) throws IllegalArgumentException, ArithmeticException {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
// ... further code
try {
// ... potentially risky arithmetic operation
} catch (ArithmeticException e) {
System.out.println("Caught arithmetic exception: " + e.getMessage());
throw e; // rethrow the caught exception
}
}
public static void main(String[] args) {
Example example = new Example();
try {
example.divide(10, 0);
} catch (IllegalArgumentException | ArithmeticException e) {
System.out.println("Caught or rethrown exception: " + e.getMessage());
}
}
}
在这个例子中,我们重写了divide
方法可能抛出的IllegalArgumentException
和ArithmeticException
。如果捕获到这些异常,我们会根据需要打印异常信息,并重新抛出异常,以保持程序的控制流。
还没有评论,来说两句吧...