Java基础异常详解

Java基础异常详解

Java中的异常是用于处理程序运行时出现的错误或异常情况的一种机制。

异常本身也是一个类。

异常分为两种类型:编译时异常(Checked Exception)和运行时异常(Unchecked Exception)。

编译时异常(Checked Exception):

编译时异常是在代码编译阶段就能够被检测到的异常,程序员必须在代码中显式处理这些异常,否则编译不会通过。常见的编译时异常包括:

  • IOException:输入输出异常,如文件操作中的读写错误。
  • SQLException:数据库访问异常。
  • ClassNotFoundException:类未找到异常。
  • InterruptedException:线程中断异常等。

处理编译时异常的方式:

  • 使用try-catch块捕获异常并处理。

  • 使用throws关键字在方法声明中抛出异常,让调用者处理。

    以下是一些常见的编译时异常的代码示例:

    1. IOException - 输入输出异常

      import java.io.*;
      
      public class IOExceptionExample {
          public static void main(String[] args) {
              try {
                  FileReader fileReader = new FileReader("file.txt");
                  // 读取文件内容
              } catch (IOException e) {
                  System.out.println("文件读取发生异常: " + e.getMessage());
              }
          }
      }
      
    2. SQLException - 数据库访问异常

      import java.sql.*;
      
      public class SQLExceptionExample {
          public static void main(String[] args) {
              try {
                  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
                  // 执行数据库操作
              } catch (SQLException e) {
                  System.out.println("数据库操作发生异常: " + e.getMessage());
              }
          }
      }
      
    3. ClassNotFoundException - 类未找到异常

      public class ClassNotFoundExceptionExample {
          public static void main(String[] args) {
              try {
                  Class.forName("com.example.MyClass");
              } catch (ClassNotFoundException e) {
                  System.out.println("未找到指定类: " + e.getMessage());
              }
          }
      }
      
    4. InterruptedException - 线程中断异常

      public class InterruptedExceptionExample {
          public static void main(String[] args) {
              Thread thread = new Thread(() -> {
                  try {
                      Thread.sleep(1000);
                  } catch (InterruptedException e) {
                      System.out.println("线程被中断: " + e.getMessage());
                  }
              });
      
              thread.start();
              thread.interrupt();
          }
      }
      

      我们通过使用try-catch块来捕获编译时异常并进行处理。

运行时异常(Unchecked Exception):

运行时异常是在程序运行时才会被抛出的异常,无需在代码中显式处理。如果不处理运行时异常,程序将会终止执行。常见的运行时异常包括:

  • ullPointerException:空指针异常,当尝试访问一个空引用时抛出。

  • ArrayIndexOutOfBoundsException:数组索引越界异常。

  • IllegalArgumentException:非法参数异常,当传递非法参数给方法时抛出。

  • ArithmeticException:算术异常,如除零操作。

  • ClassCastException:类转换异常,当尝试将一个对象强制转换成不兼容的类型时抛出。

运行时异常通常是由程序逻辑错误引起的,因此应该通过代码审查和测试来避免。

以下是一些常见的运行时异常的示例代码:

  1. NullPointerException - 空指针异常:
public class NullPointerExceptionExample {
    public static void main(String[] args) {
        String str = null;
        try {
            int length = str.length();  // 这里会抛出NullPointerException
        } catch (NullPointerException e) {
            System.out.println("发生空指针异常: " + e.getMessage());
        }
    }
}
  1. ArrayIndexOutOfBoundsException - 数组索引越界异常:
public class ArrayIndexOutOfBoundsExceptionExample {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        try {
            int value = arr[5];  // 这里会抛出ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("发生数组索引越界异常: " + e.getMessage());
        }
    }
}
  1. IllegalArgumentException - 非法参数异常:
public class IllegalArgumentExceptionExample {
    public static void main(String[] args) {
        try {
            int age = -5;
            if (age < 0) {
                throw new IllegalArgumentException("年龄不能为负数");
            }
        } catch (IllegalArgumentException e) {
            System.out.println("发生非法参数异常: " + e.getMessage());
        }
    }
}
  1. ArithmeticException - 算术异常:
public class ArithmeticExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // 这里会抛出ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("发生算术异常: " + e.getMessage());
        }
    }
}
  1. ClassCastException - 类转换异常:
public class ClassCastExceptionExample {
    public static void main(String[] args) {
        try {
            Object obj = "Hello";
            Integer num = (Integer) obj;  // 这里会抛出ClassCastException
        } catch (ClassCastException e) {
            System.out.println("发生类转换异常: " + e.getMessage());
        }
    }
}

异常处理的方法:

  • try-catch语句块:使用try-catch块捕获异常并在catch块中进行处理。
try {
    // 可能抛出异常的代码
} catch (ExceptionType e) {
    // 异常处理代码
}
  • throws关键字:在方法声明中使用throws关键字抛出异常,让调用者处理。
public void methodName() throws ExceptionType {
    // 方法体
}
  • finally块:finally块中的代码无论是否发生异常都会被执行,常用于资源的释放等操作。
try {
    // 可能抛出异常的代码
} catch (ExceptionType e) {
    // 异常处理代码
} finally {
    // 最终执行的代码,如关闭文件等
}

异常处理有助于使程序更健壮,能够更好地应对各种异常情况。在处理异常时,应根据具体情况选择合适的处理方式,以保证程序的正确性和稳定性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值