面试题答案
一键面试-
NullPointerException:当应用程序试图在需要对象的地方使用
null
时抛出。- 捕获处理:在可能出现空指针的地方进行
null
检查,例如:
String str = null; if (str!= null) { int length = str.length(); }
也可以使用
Optional
类来更优雅地处理可能为空的值。 - 捕获处理:在可能出现空指针的地方进行
-
IndexOutOfBoundsException:当对数组、字符串或集合进行索引操作时,索引超出范围就会抛出。常见的子类有
ArrayIndexOutOfBoundsException
和StringIndexOutOfBoundsException
。- 捕获处理:在访问数组或集合元素之前,确保索引在有效范围内。例如:
int[] arr = new int[5]; int index = 10; if (index >= 0 && index < arr.length) { int value = arr[index]; }
对于集合,使用
size()
方法来检查大小与索引关系。 -
ClassCastException:当试图将对象强制转换为不是实例的子类类型时抛出。
- 捕获处理:在进行强制类型转换之前,使用
instanceof
关键字进行类型检查。例如:
Object obj = new Integer(10); if (obj instanceof String) { String str = (String) obj; }
- 捕获处理:在进行强制类型转换之前,使用
-
ArithmeticException:当出现异常的算术条件时抛出,例如除以零。
- 捕获处理:在进行除法等算术运算之前,对除数进行检查,避免除以零。例如:
int dividend = 10; int divisor = 0; if (divisor!= 0) { int result = dividend / divisor; }
也可以使用
try - catch
块捕获异常:try { int result = dividend / divisor; } catch (ArithmeticException e) { System.out.println("除数不能为零"); }
-
IllegalArgumentException:当方法接收到非法或不适当的参数时抛出。
- 捕获处理:在方法内部,对参数进行有效性检查,如果参数不合法,抛出该异常或者在调用方法处捕获处理。例如:
public void printPositiveNumber(int num) { if (num < 0) { throw new IllegalArgumentException("参数必须为正数"); } System.out.println(num); }
在调用处:
try { printPositiveNumber(-1); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
-
ConcurrentModificationException:当在迭代集合的过程中,集合被意外修改时抛出。
- 捕获处理:使用迭代器的
remove()
方法来修改集合,而不是直接调用集合的add
或remove
方法。例如:
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3)); Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()) { Integer num = iterator.next(); if (num == 2) { iterator.remove(); } }
也可以使用
CopyOnWriteArrayList
等线程安全的集合,它在迭代时不会抛出该异常。 - 捕获处理:使用迭代器的