十大常见异常

  1. NullPointerException
    当应用程序试图访问一个为空的对象时抛出此异常。

    String str = null; System.out.println(str.length()); // 抛出 NullPointerException
  2. ArrayIndexOutOfBoundsException
    当访问数组时索引超出范围时抛出此异常。

    int[] arr = new int[5]; System.out.println(arr[5]); // 抛出 ArrayIndexOutOfBoundsException
  3. ClassCastException
    当试图将一个对象强制转换为不是实例的类时抛出此异常。

    
    Object obj = new Integer(100); String str = (String) obj; // 抛出 ClassCastException
  4. ArithmeticException
    当进行非法算术运算时抛出此异常,例如除以零。

    
    int result = 10 / 0; // 抛出 ArithmeticException
  5. IllegalArgumentException
    当方法接收到不合法或不适当的参数时抛出此异常。

    Thread thread = new Thread(); thread.setPriority(11); // 抛出 IllegalArgumentException

    NumberFormatException

  6. 当转换字符串为数字类型失败时抛出此异常。

    
    String number = "abc"; int num = Integer.parseInt(number); // 抛出 NumberFormatException
  7. IOException
    当出现输入输出错误时抛出此异常,通常与文件操作相关。

    FileReader file = new FileReader("nonexistentfile.txt"); // 抛出 FileNotFoundException,IOException的子类
  8. InterruptedException
    当线程在活动等待(如睡眠或等待)状态被中断时抛出此异常。

    Thread.sleep(1000); // 如果在这期间线程被中断,将抛出 InterruptedException
  9. StackOverflowError
    发生在递归调用超过栈大小限制时。

    public void recursiveMethod() { recursiveMethod(); // 会抛出 StackOverflowError }
  10. OutOfMemoryError
    当Java虚拟机无法分配更多内存时抛出此错误。

    List<String> list = new ArrayList<>(); while (true) { list.add("Memory Leak"); // 会抛出 OutOfMemoryError }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值