try catch finally 案例
时间: 2023-11-23 20:54:30 浏览: 35
Java中的try-catch-finally语句用于处理异常。下面是一个简单的try-catch-finally案例:
```
public class TryCatchFinallyExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // 这里会抛出一个ArithmeticException异常
} catch (ArithmeticException e) {
System.out.println("发生了算术异常:" + e.getMessage());
} finally {
System.out.println("这里是finally块,无论是否发生异常都会执行。");
}
}
}
```
在上面的代码中,我们故意将一个整数除以0,这会导致一个ArithmeticException异常的抛出。在try块中,我们捕获了这个异常,并在catch块中打印了异常信息。无论是否发生异常,finally块中的代码都会被执行。
相关问题
try catch finally代码案例
以下是一个简单的 try catch finally 代码案例,其中 try 块用于执行可能会抛出异常的代码,catch 块用于捕获和处理异常,finally 块用于执行在 try 和 catch 块之后必须执行的代码(例如关闭资源):
```
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TryCatchFinallyExample {
public static void main(String[] args) {
File file = new File("file.txt");
FileReader fr = null;
try {
fr = new FileReader(file);
char[] chars = new char[(int) file.length()];
fr.read(chars);
System.out.println(chars);
} catch (IOException e) {
System.out.println("文件读取异常:" + e.getMessage());
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
System.out.println("文件关闭异常:" + e.getMessage());
}
}
}
}
}
```
在上述代码中,我们尝试读取名为 "file.txt" 的文件。如果文件不存在或读取时发生异常,catch 块将捕获并处理异常。无论是否发生异常,finally 块都将关闭文件读取器,以确保资源被正确释放。
Java异常处理程序案例
以下是一个简单的Java异常处理程序案例:
```java
import java.util.Scanner;
public class ExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("请输入一个整数:");
int num1 = scanner.nextInt();
System.out.print("请输入另一个整数:");
int num2 = scanner.nextInt();
int result = num1 / num2;
System.out.println("结果为:" + result);
} catch (ArithmeticException e) {
System.out.println("除数不能为0!");
} catch (Exception e) {
System.out.println("输入有误,请输入整数!");
} finally {
scanner.close();
}
}
}
```
在上述程序中,我们使用了`try-catch`语句块来捕获异常。当用户输入的除数为0时,会抛出`ArithmeticException`异常,程序会输出"除数不能为0!";当用户输入的不是整数时,会抛出`Exception`异常,程序会输出"输入有误,请输入整数!"。无论是否发生异常,`finally`语句块中的代码总会被执行,这里我们关闭了Scanner对象。