面试中经常会被问到,列举几种常见异常。怎么能被这个难倒呢?
下面随便列举些,以及触发例子。
文章目录
- NullPointerException
- ArithmeticException
- NumberFormatException
- StringIndexOutOfBoundsException
- ArrayIndexOutOfBoundsException
- IllegalArgumentException
- 非运行时异常
- ClassNotFoundException
- FileNotFoundException
- 扩展
NullPointerException
空指针异常
String string = null;
string.length();
ArithmeticException
算术异常
int n=0/0;
顺便拓展下: 1.0/0 会报异常吗?
double d=1.0/0;
不会报异常,返回值是Infinity。
NumberFormatException
数字格式化异常
Double.valueOf("");
StringIndexOutOfBoundsException
字符串下标越界异常
String string="";
string.charAt(2);
ArrayIndexOutOfBoundsException
数组下标越界异常
// String[] args={}; // main方法中不用这一句
System.out.println(args[5]);
IllegalArgumentException
参数不合法异常
Assert.hasText(null,"用户名为必填");
非运行时异常
ClassNotFoundException
类找不到异常
try {
Class<?> classObject = Class.forName("你找不到个类");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
FileNotFoundException
文件找不到异常
try {
FileInputStream asfasf = new FileInputStream("桃花岛");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
扩展