Java核心异常类
异常类的层次结构: Throwable
可投掷
Throwable 类是 Java 语言中所有错误和异常的超类。只有属于该类(或其子类之一)实例的对象才会被 Java 虚拟机抛出或者可以被 Java throw 语句抛出。参考
实际上,开发人员通常不直接使用 Throwable。相反,它作为其两个直接子类的基础:Error 和 Exception。
1 2 3 4 5 | try {
} catch (Throwable t) {
throw new Throwable(t);
}
|
登录后复制
错误
Error 是 Throwable 的子类,它指示合理的应用程序不应尝试捕获的严重问题。错误通常代表 JVM 本身发生的异常情况参考
异常情况意味着问题通常是由应用程序无法控制的因素引起的,并且通常无法恢复。例如:OutOfMemoryError、StackOverflowError
![Deep Dive into Java Exceptions](https://img.php.cn/upload/article/000/000/000/172401846448822.png)
例外
异常是指程序执行过程中发生的意外事件或情况,我们应该尝试catch。通过捕获异常,我们应该能够优雅地处理意外情况,确保程序不会崩溃。
1 2 3 4 5 6 | int[] arr = {1, 2, 3};
try {
System.out.println(arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println( "Unchecked Exception: " + e.getMessage());
}
|
登录后复制
例外的类型
java中有两种类型的异常。参考
检查异常
检查异常就像您知道可能会出错的情况,因此您需要为此做好计划。它们必须使用 try-catch 块捕获,或者使用 throws 子句在方法签名中声明。如果一个方法可以抛出一个已检查的异常并且您不处理它,则程序将无法编译。
1 2 3 4 5 6 | try {
readFile( "nonexistent.txt" );
} catch (FileNotFoundException e) {
System.out.println( "Checked Exception: " + e.getMessage());
}
|
登录后复制
1 2 3 4 | public void getData() throws SQLException {
throw new SQLException( "err" );
}
|
登录后复制
未经检查的异常
未检查的异常,又名。运行时异常是 Java 编译器不需要您处理的异常。它们是 RuntimeException 的子类。与检查异常不同,这些异常不需要在方法签名中捕获或声明。它们通常表示编程错误,例如逻辑缺陷、API 使用不正确或违反代码中的假设。
1 2 | String text = null;
System.out.println(text.length());
|
登录后复制
Java异常的常见类型
NullPointerException:当应用程序尝试使用尚未初始化的对象引用时发生。
1 2 3 4 5 6 | String text = null;
try {
System.out.println(text.length());
} catch (NullPointerException e) {
System.out.println( "Caught a NullPointerException: " + e.getMessage());
}
|
登录后复制
ArrayIndexOutOfBoundsException:当尝试访问具有非法索引的数组时抛出。
1 2 3 4 5 6 | int[] numbers = {1, 2, 3};
try {
int value = numbers[5];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println( "Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
}
|
登录后复制
IllegalArgumentException:当方法接收到不适当的参数时抛出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class IllegalArgumentExample {
public static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException( "Age cannot be negative" );
}
System.out.println( "Age set to: " + age);
}
public static void main(String[] args) {
try {
setAge(-5);
} catch (IllegalArgumentException e) {
System.out.println( "Caught an IllegalArgumentException: " + e.getMessage());
}
}
}
|
登录后复制
如何处理异常
尝试捕捉
当您想要处理代码块中可能抛出的特定异常时,请使用 try-catch
1 2 3 4 5 | try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println( "Caught an ArithmeticException: " + e.getMessage());
}
|
登录后复制
多重捕获
当你想以类似的方式处理多种异常类型时,请使用多重捕获
1 2 3 4 5 6 | try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
System.out.println( "Caught an exception: " + e.getMessage());
}
|
登录后复制
尝试资源
当您处理使用后需要关闭的资源(例如文件、套接字或数据库连接)时,请使用 try-with-resources。
1 2 3 4 5 6 7 8 | try (BufferedReader br = new BufferedReader( new FileReader( "file.txt" ))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println( "Caught an IOException: " + e.getMessage());
}
|
登录后复制
最后
当您需要确保无论是否抛出异常都执行某些代码时,请使用finally块
1 2 3 4 5 6 7 8 9 | try {
file = new FileReader( "file.txt" );
} catch (IOException e) {
System.out.println( "Caught an IOException: " + e.getMessage());
} finally {
if (file != null) {
file.close();
}
}
|
登录后复制
异常处理的最佳实践
不要忽略异常:异常应该得到适当的处理,而不仅仅是捕获和忽略。
1 2 3 4 5 | try {
file = new FileReader( "file.txt" );
} catch (IOException ignored) {
}
|
登录后复制
使用特定异常:使用特定异常而不是通用异常。
1 2 3 4 5 6 7 8 | try {
String text = null;
text.length();
} catch (Exception e) {
System.err.println( "An error occurred: " + e.getMessage());
}
|
登录后复制
正确处理方法:
1 2 3 4 5 6 7 8 9 10 11 | try {
String text = null;
text.length();
} catch (NullPointerException e) {
System.err.println( "Null pointer exception: " + e.getMessage());
} catch (Exception e) {
System.err.println( "An error occurred: " + e.getMessage());
}
|
登录后复制
清洁资源处理:始终关闭资源以避免内存泄漏
1 2 3 4 5 6 7 8 9 | FileReader fileReader = null;
try {
fileReader = new FileReader( "file.txt" );
} catch (IOException e) {
System.err.println( "File not found: " + e.getMessage());
} finally {
fileReader.close();
}
|
登录后复制
自定义异常:当标准异常不适合特定错误条件时创建自定义异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Example {
public void performOperation() throws CustomException {
throw new CustomException( "Custom error message" );
}
public static void main(String[] args) {
Example example = new Example();
try {
example.performOperation();
} catch (CustomException e) {
System.err.println( "Caught custom exception: " + e.getMessage());
}
}
}
|
登录后复制
日志记录:记录异常以进行调试和维护。
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Example {
private static final Logger logger = Logger.getLogger(Example. class .getName());
public void riskyMethod() {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
logger.severe( "An arithmetic error occurred: " + e.getMessage());
}
}
}
|
登录后复制
避免过度使用异常:警告不要使用异常来控制流程;它们应该只用于处理真正的特殊情况。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class Example {
public void process(int[] array ) {
try {
if ( array .length < 5) {
throw new ArrayIndexOutOfBoundsException( "Array too small" );
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println( "Handled array size issue." );
}
}
}
|
登录后复制
正确处理方法:
1 2 3 4 5 6 7 8 9 10 | public class Example {
public void process(int[] array ) {
if ( array .length >= 5) {
} else {
System.out.println( "Array is too small." );
}
}
}
|
登录后复制
任何反馈都会有帮助:)
以上是深入研究 Java 异常的详细内容。更多信息请关注PHP中文网其他相关文章!