Java常见的异常都有哪些?举例说明
2019-04-21 本文已影响0人
黑咔
运行时异常(unchecked,RuntimeException)
- NullPointerException(空指针)
int[] arr = null;
System.out.println(arr[3]);
String str = "abc";
str = null;
System.out.println(str.charAt(0));
- IndexOutOfBoundsException(角标越界)
//ArrayIndexOutOfBoundsException 数组角标越界
int[] arr = new int[10];
System.out.println(arr[10]);
//StringIndexOutOfBoundsException 字符串角标越界
String str = "abc";
System.out.println(str.charAt(3));
- ClassCastException(类型转换异常)
Object obj = new Date();
String str = (String)obj;
- NumberFormatException(数值格式转换异常)
String str = "123";
str = "abc";
int num = Integer.parseInt(str);
- InputMismatchException(输入不匹配的类型)
Scanner scanner = new Scanner(System.in);
int score = scanner.nextInt();
System.out.println(score);
//在控制台输入字符串
scanner.close();
- ArithmeticException(算术异常)
int a = 10;
int b = 0;
System.out.println(a / b);
编译时异常(checked)
-
FileNotFoundException
FileNotFoundException
-
IOException
IOException