首页 > Java > java教程 > 正文

深入研究 Java 异常

PHPz
发布: 2024-08-19 06:01:02
原创
403 人浏览过

Java核心异常类

异常类的层次结构: Throwable

可投掷

Throwable 类是 Java 语言中所有错误和异常的超类。只有属于该类(或其子类之一)实例的对象才会被 Java 虚拟机抛出或者可以被 Java throw 语句抛出。参考

实际上,开发人员通常不直接使用 Throwable。相反,它作为其两个直接子类的基础:Error 和 Exception。

try {
 // some process
} catch (Throwable t) {
    throw new Throwable(t);
}
登录后复制

错误

Error 是 Throwable 的子类,它指示合理的应用程序不应尝试捕获的严重问题。错误通常代表 JVM 本身发生的异常情况参考

异常情况意味着问题通常是由应用程序无法控制的因素引起的,并且通常无法恢复。例如:OutOfMemoryError、StackOverflowError

Deep Dive into Java Exceptions

例外

异常是指程序执行过程中发生的意外事件或情况,我们应该尝试catch。通过捕获异常,我们应该能够优雅地处理意外情况,确保程序不会崩溃。

int[] arr = {1, 2, 3};
try {
    System.out.println(arr[3]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Unchecked Exception: " + e.getMessage());
}
登录后复制

 

例外的类型

java中有两种类型的异常。参考

检查异常

检查异常就像您知道可能会出错的情况,因此您需要为此做好计划。它们必须使用 try-catch 块捕获,或者使用 throws 子句在方法签名中声明。如果一个方法可以抛出一个已检查的异常并且您不处理它,则程序将无法编译。

// Checked exception
try {
    readFile("nonexistent.txt");
} catch (FileNotFoundException e) {
    System.out.println("Checked Exception: " + e.getMessage());
}
登录后复制
// Checked exception
public void getData() throws SQLException { // throw SQLException
    throw new SQLException("err");
}
登录后复制

未经检查的异常

未检查的异常,又名。运行时异常是 Java 编译器不需要您处理的异常。它们是 RuntimeException 的子类。与检查异常不同,这些异常不需要在方法签名中捕获或声明。它们通常表示编程错误,例如逻辑缺陷、API 使用不正确或违反代码中的假设。

String text = null;
System.out.println(text.length()); // This will throw a NullPointerException
登录后复制

 

Java异常的常见类型

NullPointerException:当应用程序尝试使用尚未初始化的对象引用时发生。

String text = null; // text is not initialized
try {
    System.out.println(text.length()); // Attempting to call length() on a null reference
} catch (NullPointerException e) {
    System.out.println("Caught a NullPointerException: " + e.getMessage());
}
登录后复制

ArrayIndexOutOfBoundsException:当尝试访问具有非法索引的数组时抛出。

int[] numbers = {1, 2, 3};
try {
    int value = numbers[5]; // Attempting to access index 5, which is out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
}
登录后复制

IllegalArgumentException:当方法接收到不适当的参数时抛出。

public class IllegalArgumentExample {
    public static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative"); // Illegal argument
        }
        System.out.println("Age set to: " + age);
    }

    public static void main(String[] args) {
        try {
            setAge(-5); // Passing a negative age, which is illegal
        } catch (IllegalArgumentException e) {
            System.out.println("Caught an IllegalArgumentException: " + e.getMessage());
        }
    }
}
登录后复制

 

如何处理异常

尝试捕捉

当您想要处理代码块中可能抛出的特定异常时,请使用 try-catch

try {
    int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Caught an ArithmeticException: " + e.getMessage());
}
登录后复制

多重捕获

当你想以类似的方式处理多种异常类型时,请使用多重捕获

try {
    String str = null;
    System.out.println(str.length()); // This will throw NullPointerException
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught an exception: " + e.getMessage());
}
登录后复制

尝试资源

当您处理使用后需要关闭的资源(例如文件、套接字或数据库连接)时,请使用 try-with-resources。

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块

try {
    file = new FileReader("file.txt");
} catch (IOException e) {
    System.out.println("Caught an IOException: " + e.getMessage());
} finally {
    if (file != null) {
        file.close(); // Ensure the file is closed
    }
}
登录后复制

 

异常处理的最佳实践

不要忽略异常:异常应该得到适当的处理,而不仅仅是捕获和忽略。

try {
    file = new FileReader("file.txt");
} catch (IOException ignored) {
    // ignored
}
登录后复制

使用特定异常:使用特定异常而不是通用异常。

try {
    // Code that may throw exceptions
    String text = null;
    text.length();
} catch (Exception e) {
    // Too broad; will catch all exceptions
    System.err.println("An error occurred: " + e.getMessage());
}
登录后复制

正确处理方法:

try {
    // Code that may throw exceptions
    String text = null;
    text.length();
} catch (NullPointerException e) {
    // Handle specific exception
    System.err.println("Null pointer exception: " + e.getMessage());
} catch (Exception e) {
    // Handle other exceptions
    System.err.println("An error occurred: " + e.getMessage());
}
登录后复制

清洁资源处理:始终关闭资源以避免内存泄漏

FileReader fileReader = null;
try {
    fileReader = new FileReader("file.txt");
    // Read from the file
} catch (IOException e) {
    System.err.println("File not found: " + e.getMessage());
} finally {
   fileReader.close(); // clouse resources
}
登录后复制

自定义异常:当标准异常不适合特定错误条件时创建自定义异常。

// Custom Exception
public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

// Usage
public class Example {
    public void performOperation() throws CustomException {
        // Some condition
        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());
        }
    }
}
登录后复制

日志记录:记录异常以进行调试和维护。

public class Example {
    private static final Logger logger = Logger.getLogger(Example.class.getName());

    public void riskyMethod() {
        try {
            // Code that may throw an exception
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            // Log the exception
            logger.severe("An arithmetic error occurred: " + e.getMessage());
        }
    }
}
登录后复制

避免过度使用异常:警告不要使用异常来控制流程;它们应该只用于处理真正的特殊情况。

public class Example {
    public void process(int[] array) {
        try {
            // Using exceptions to control flow
            if (array.length < 5) {
                throw new ArrayIndexOutOfBoundsException("Array too small");
            }
            // Process array
        } catch (ArrayIndexOutOfBoundsException e) {
            // Handle exception
            System.out.println("Handled array size issue.");
        }
    }
}
登录后复制

正确处理方法:

public class Example {
    public void process(int[] array) {
        if (array.length >= 5) {
            // Process array
        } else {
            // Handle the condition without using exceptions
            System.out.println("Array is too small.");
        }
    }
}
登录后复制

 
任何反馈都会有帮助:)

以上是深入研究 Java 异常的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!