Demo.java:
package cn.xxx.demo; import java.util.NoSuchElementException; /* * 多catch写在一起 * 细节: * catch小括号中,写的是异常类的类名 * 多个catch有顺序之分。 * * 平级异常(没有继承关系): 抛出的异常类之间,没有继承关系,没有顺序 * NullPointerException extends RuntimeException * NoSuchElementException extends RuntimeException * ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException extends RuntimeException * * 上下级关系的异常 * NullPointerException extends RuntimeException extends Exception * 越高级的父类,写在下面 */ public class Demo { public static void main(String[] args) { try{ // ... }catch(NullPointerException ex){ // 子级异常写上面 // ... } catch(Exception ex){ // 父级异常写下面 // ... } } public static void function(int a)throws NullPointerException,Exception{ if(a == 0){ throw new NullPointerException(); } if(a == 1){ throw new Exception(); } } }