Exception

Exception 分两种: 编译时异常和RuntimeException.
编译时异常必须要处理。
异常处理的五个关键字:throw,throws,try..catch,finally
1.使用throw抛出异常:

NullPointerException和 ArrayIndexOutOfBoundsException 都是运行时异常。
public static void main(String[] args) { int[] arr = null; int value = getElement(arr, 0); System.out.println(value); } public static int getElement(int[] arr,int index) { if(arr == null) { throw new NullPointerException("The array is null!"); } if(index<0||index>arr.length-1) { throw new ArrayIndexOutOfBoundsException("Index out of bounds:"+index); } int value = arr[index]; return value; } Exception in thread "main" java.lang.NullPointerException: The array is null! at exception.TestThrow.getElement(TestThrow.java:14) at exception.TestThrow.main(TestThrow.java:8)
2.使用throws处理异常:

3.使用try...catch处理异常

4.finally

public static void main(String[] args) { int[] arr = null; int index = 0; try { int value = getElement(arr, index); System.out.println("Get value: "+value); return; } catch (Exception e) { System.out.println(e); return; }finally { System.out.println("finally里面的代码");//这段代码都会打印出来 } } public static int getElement(int[] arr,int index) { if(arr == null) { throw new NullPointerException("The array is null!"); } if(index<0||index>arr.length-1) { throw new ArrayIndexOutOfBoundsException("Index out of bounds:"+index); } int value = arr[index]; return value; }
如果finally里面有return语句,那么永远返回finally里面的结果。(要尽量避免该情况)
自定义异常:


浙公网安备 33010602011771号