Java详细讲解异常Exception的处理
什么是异常Exception
异常(Exception)指的是程序运行过程中不正常(错误)的情况,例如输入输出错误、计算错误、网络连接中断等情况。一般来说,出现异常会导致程序停止运行。
在Java中,异常被抛出后可以被程序处理,以免程序崩溃。Java中的异常分为两种类型:受检异常(Checked Exception) 和 未受检异常(Unchecked Exception)。
受检异常必须通过异常处理(try-catch语句或者throws声明)进行处理,否则代码无法编译通过。例如,IOException和SQLException异常就属于受检异常。
未受检异常不需要在代码中明确进行处理,即使不对它们进行处理,代码仍然可以编译通过。例如,NullPointerException和ArrayIndexOutOfBoundsException异常就属于未受检异常。
异常处理
异常的处理主要有两种方式:
- try-catch-finally语句:被包含在 try 语句块中的代码是能抛出异常的。当程序中抛出异常后,会寻找一个符合异常类型的 catch 块;如果找不到,则会将异常交给更高一级的 try-catch 块。如果所有的 catch 块都没捕捉到该异常,异常就被传递到运行时系统。
- throws 声明:使用 throws 声明来抛出异常,在方法名后边加上 throws 异常名。这种方式将异常交给方法的调用者处理。
以下是两个示例说明:
示例一
public class TestException {
public static void main(String[] args) {
try {
int num = divide(6, 0);
System.out.println("Result: " + num);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
} finally {
System.out.println("Finally block is always executed.");
}
}
public static int divide(int dividend, int divisor) {
return dividend/divisor;
}
}
上述代码中,方法 divide()
抛出了一个除数为0的异常,因为在程序运行过程中除数为0是不能处理的。因此使用 try-catch-finally 语句捕获并处理异常。当被执行到 catch 块时,程序将会打印出 "Arithmetic Exception: / by zero"。最后,finally 块会被执行。
示例二
public class TestException {
public static void main(String[] args) throws Exception {
readFile("file.txt");
}
public static void readFile(String fileName) throws Exception {
File file = new File(fileName);
FileInputStream stream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader in = new BufferedReader(reader);
String s;
while ((s = in.readLine()) != null) {
System.out.println(s);
}
in.close();
}
}
上述代码中,readFile() 方法读取一个文件。该方法使用了 throws 声明,在方法名后边加上 throws Exception,表示该方法可能会抛出一个异常。如果该方法抛出异常,程序的调用者就需要处理异常,如果不处理将会导致编译错误。
总结
Java语言中对异常进行了严谨的管理,程序员可以很方便地通过 try-catch 或 throws 声明来处理异常。在编程过程中,我们应该多考虑程序中出现异常的情况,设计相应的异常处理方式,以保证程序的运行质量。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java详细讲解异常Exception的处理 - Python技术站