异常是在程序执行过程中出现的错误或异常情况,而异常处理就是针对这些异常情况进行处理,以保证程序的正常运行。在Java中,异常分为两种类型:检查异常(checked exception)和非检查异常(unchecked exception)。检查异常需要在代码中显式地进行处理,否则编译器会报错;而非检查异常可以选择性地进行处理。下面是一个简单的示例代码,演示了如何使用try-catch语句进行异常处理:
public class ExceptionHandlingExample { public static void main(String[] args) { try { // 可能抛出异常的代码块 int result = divide(10, 0); System.out.println("结果:" + result); } catch (ArithmeticException e) { // 异常处理代码块 System.out.println("除数不能为零"); } } public static int divide(int dividend, int divisor) { return dividend / divisor; } }
在上述代码中,我们定义了一个divide()方法用于进行除法运算。在main()方法中,我们调用divide()方法,并使用try-catch语句捕获可能抛出的ArithmeticException异常。如果除数为零,就会触发该异常,然后进入catch代码块,打印出"除数不能为零"的提示信息。除了try-catch语句外,Java还提供了finally语句用于定义无论是否发生异常都会执行的代码块。例如:public class ExceptionHandlingExample { public static void main(String[] args) { try { // 可能抛出异常的代码块 int result = divide(10, 0); System.out.println("结果:" + result); } catch (ArithmeticException e) { // 异常处理代码块 System.out.println("除数不能为零"); } finally { // 无论是否发生异常,都会执行的代码块 System.out.println("程序结束"); } } public static int divide(int dividend, int divisor) { return dividend / divisor; } }
在上述代码中,我们添加了一个finally代码块,用于输出"程序结束"的提示信息。