-
NullPointerException
当应用程序试图访问一个为空的对象时抛出此异常。String str = null; System.out.println(str.length()); // 抛出 NullPointerException
-
ArrayIndexOutOfBoundsException
当访问数组时索引超出范围时抛出此异常。int[] arr = new int[5]; System.out.println(arr[5]); // 抛出 ArrayIndexOutOfBoundsException
-
ClassCastException
当试图将一个对象强制转换为不是实例的类时抛出此异常。Object obj = new Integer(100); String str = (String) obj; // 抛出 ClassCastException
-
ArithmeticException
当进行非法算术运算时抛出此异常,例如除以零。int result = 10 / 0; // 抛出 ArithmeticException
-
IllegalArgumentException
当方法接收到不合法或不适当的参数时抛出此异常。Thread thread = new Thread(); thread.setPriority(11); // 抛出 IllegalArgumentException
NumberFormatException
-
当转换字符串为数字类型失败时抛出此异常。
String number = "abc"; int num = Integer.parseInt(number); // 抛出 NumberFormatException
-
IOException
当出现输入输出错误时抛出此异常,通常与文件操作相关。FileReader file = new FileReader("nonexistentfile.txt"); // 抛出 FileNotFoundException,IOException的子类
-
InterruptedException
当线程在活动等待(如睡眠或等待)状态被中断时抛出此异常。Thread.sleep(1000); // 如果在这期间线程被中断,将抛出 InterruptedException
-
StackOverflowError
发生在递归调用超过栈大小限制时。public void recursiveMethod() { recursiveMethod(); // 会抛出 StackOverflowError }
-
OutOfMemoryError
当Java虚拟机无法分配更多内存时抛出此错误。List<String> list = new ArrayList<>(); while (true) { list.add("Memory Leak"); // 会抛出 OutOfMemoryError }
十大常见异常
最新推荐文章于 2024-09-14 18:46:05 发布