Java异常处理机制:捕获与抛出示例案例

原创 妖狐艹你老母 2024-11-15 08:15 102阅读 0赞

在Java编程中,异常处理机制是确保程序在出现错误或异常情况时能够正常运行的重要手段。主要包括两种操作:捕获(catch)和抛出(throw)。

  1. 捕获异常:

    1. try {
    2. // 有可能产生异常的代码
    3. int divisionByZero = 5 / 0;
    4. } catch (ArithmeticException e) {
    5. System.out.println("捕获到除以零的异常: " + e.getMessage());
    6. }

    在这个例子中,我们尝试执行5 / 0,这会抛出一个ArithmeticException。然后我们在catch块中捕获这个异常,并打印出异常的消息。

  2. 抛出异常:

    1. public class ExceptionExample {
    2. public void throwException() throws Exception {
    3. // 在这里产生异常的代码
    4. String invalidInput = "Hello, World!";
    5. if (invalidInput.isEmpty()) {
    6. throw new IllegalArgumentException("Invalid input");
    7. }
    8. }
    9. public static void main(String[] args) {
    10. try {
    11. ExceptionExample example = new ExceptionExample();
    12. example.throwException();
    13. } catch (IllegalArgumentException e) {
    14. System.out.println("捕获到输入无效的异常: " + e.getMessage());
    15. } catch (Exception anyException) {
    16. System.out.println("捕获到任何类型的异常: " + anyException);
    17. }
    18. }
    19. }

    在这个例子中,我们在throwException()方法中产生一个IllegalArgumentException。然后在main()方法中的try-catch块中捕获这个异常,并打印出异常的消息。

总结:Java的异常处理机制通过捕获和抛出异常来确保程序在遇到错误时能够保持稳定运行。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,102人围观)

还没有评论,来说两句吧...

相关阅读