Java 异常处理
Java 异常处理
在本教程中,我们将通过示例了解 Java 中异常处理的不同方法。
在上一个教程中,我们学习了 Java 异常。我们知道异常会异常终止程序的执行。
这就是为什么处理异常很重要。下面列出了在 Java 中处理异常的不同方法。
- try...catch 块
- 终于屏蔽了
- throw 和 throws 关键字
1. Java try...catch 块
try-catch 块用于处理 Java 中的异常。这是 try...catch 的语法 块:
try {
// code
}
catch(Exception e) {
// code
}
在这里,我们将可能产生异常的代码放在 try 中 堵塞。每 try 块后跟 catch 块。
当异常发生时,被catch捕获 堵塞。 catch 没有 try 就不能使用块 块。
示例:使用 try...catch 处理异常
class Main {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
} 输出
ArithmeticException => / by zero
在示例中,我们试图将一个数字除以 0 .在这里,这段代码产生了一个异常。
为了处理异常,我们放了代码,5 / 0 try里面 堵塞。现在,当发生异常时,try 中的其余代码 块被跳过。
catch 块捕获异常并执行catch块内的语句。
如果 try 中没有任何语句 块产生异常,catch 块被跳过。
2. Java 终于阻塞了
在 Java 中,finally 不管有没有异常,block总是被执行。
finally 块是可选的。并且,对于每个 try 块,只能有一个 finally 块。
finally的基本语法 块是:
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
如果发生异常,finally 块在 try...catch 之后执行 堵塞。否则,它将在 try 块之后执行。对于每个 try 块,只能有一个finally 块。
示例:使用 finally 块处理 Java 异常
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
} 输出
ArithmeticException => / by zero This is the finally block
在上面的例子中,我们将一个数字除以 0 try 内 堵塞。在这里,此代码生成一个 ArithmeticException .
异常被 catch 捕获 堵塞。然后是 finally 块被执行。
注意 :使用 finally 是个好习惯 堵塞。这是因为它可以包含重要的清理代码,例如,
- 可能会因返回、继续或中断而意外跳过的代码
- 关闭文件或连接
3. Java throw 和 throws 关键字
Java throw 关键字用于显式抛出单个异常。
当我们 throw 一个例外,程序的流程从 try 阻止到 catch 块。
示例:使用 Java throw 处理异常
class Main {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
} 输出
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)
在上面的例子中,我们明确地抛出了 ArithmeticException 使用 throw 关键字。
同样,throws 关键字用于声明方法中可能发生的异常类型。在方法声明中使用。
示例:Java throws 关键字
import java.io.*;
class Main {
// declareing the type of exception
public static void findFile() throws IOException {
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args) {
try {
findFile();
}
catch (IOException e) {
System.out.println(e);
}
}
} 输出
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
当我们运行这个程序时,如果文件 test.txt 不存在,FileInputStream 抛出 FileNotFoundException 它扩展了 IOException 类。
findFile() 方法指定 IOException 可以扔。 main() 方法调用该方法,如果抛出异常则处理。
如果方法不处理异常,则必须在throws中指定其中可能发生的异常类型 子句。
要了解更多信息,请访问 Java throw 和 throws。
java