【JAVA】try-catch结构:异常处理的使用
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
public class Main {
public static void main(String[] args) {
int dividend = 50;
int divisor = 0;
try {
int result = dividend / divisor; // 这里会抛出ArithmeticException
} catch (ArithmeticException e) {
System.out.println("发生了除以0的算术异常,异常信息:" + e.getMessage());
} finally {
System.out.println("不论是否有异常发生,finally块中的代码都会执行。");
}
}
}
这段代码演示了如何使用try-catch结构来处理异常。在try块中,我们尝试执行可能会抛出异常的代码(这里是一个除法操作)。如果try块中的代码抛出了异常,则会被catch块捕获并处理。finally块中的代码用于清理资源或执行一些总是需要执行的代码,不管是否有异常发生。
评论已关闭