Java异常处理
1. 异常简介
在Java中,**异常(Exception)**是程序运行过程中发生的不正常情况,例如除零、数组越界、文件未找到等。异常处理的目的是提高程序的健壮性,让程序在出现错误时能够被捕获并正确处理,而不是直接崩溃。
异常分类
- 检查异常(Checked Exception):编译器要求必须处理的异常,如
IOException
。
- 非检查异常(Unchecked Exception):运行时异常,如
NullPointerException
、ArrayIndexOutOfBoundsException
。
- 错误(Error):系统级问题,如
OutOfMemoryError
,一般不处理。
2. try-catch语句
try-catch
用于捕获和处理异常。
1 2 3 4 5 6 7 8 9 10
| public class ExceptionExample { public static void main(String[] args) { try { int a = 10 / 0; } catch (ArithmeticException e) { System.out.println("捕获到异常: " + e); } System.out.println("程序继续运行"); } }
|
说明:
try
块中放可能产生异常的代码。
catch
块用于捕获指定异常并处理。
- 程序不会因为异常崩溃,仍可继续执行后续代码。
3. 多个catch块
可以针对不同类型异常使用多个catch
块。
1 2 3 4 5 6 7 8
| try { int[] arr = new int[3]; System.out.println(arr[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组越界: " + e); } catch (Exception e) { System.out.println("其他异常: " + e); }
|
4. finally语句
finally
块中的代码无论是否发生异常都会执行,常用于释放资源。
1 2 3 4 5 6 7
| try { System.out.println("打开文件"); } catch (Exception e) { System.out.println("处理异常"); } finally { System.out.println("关闭文件"); }
|
5. throws关键字
方法声明中使用throws
表示可能抛出的异常,需要调用者处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import java.io.*;
public class ThrowsExample { public static void readFile() throws IOException { FileReader file = new FileReader("test.txt"); file.read(); file.close(); }
public static void main(String[] args) { try { readFile(); } catch (IOException e) { System.out.println("捕获到IO异常: " + e); } } }
|
6. throw关键字
throw
用于手动抛出异常。
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class ThrowExample { public static void checkAge(int age) { if (age < 18) { throw new IllegalArgumentException("未满18岁"); } else { System.out.println("年龄合法"); } }
public static void main(String[] args) { checkAge(15); } }
|
7. 自定义异常
可以通过继承Exception
类来创建自定义异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class MyException extends Exception { public MyException(String message) { super(message); } }
public class CustomExceptionExample { public static void test(int number) throws MyException { if (number < 0) { throw new MyException("数字不能为负数"); } System.out.println("数字合法"); }
public static void main(String[] args) { try { test(-5); } catch (MyException e) { System.out.println("捕获自定义异常: " + e.getMessage()); } } }
|
8. 总结
Java提供了丰富的异常处理机制,包括try-catch-finally
、throw
和throws
以及自定义异常,使得程序在面对错误时更安全、可靠。掌握异常处理是写出健壮Java程序的关键。