定义三种新类型的异常。
写一个类,在该类的三个方法中抛出三种不同的异常。
然后在mian方法中调用这个类的不同方法,尝试用try catch捕获你写的异常。
public class Work2 { public static void main(String[] args) { ExceptionGenerator exceptionGenerator = new ExceptionGenerator(); //处理第一种自定义编译时异常 try { exceptionGenerator.genFirstException(); } catch (MyFirstException e) { e.printStackTrace(); } //处理第二种自定义运行时异常 try { exceptionGenerator.genSecondException(); } catch (MySecondException e) { e.printStackTrace(); } //处理第三种自定义编译时异常 try { exceptionGenerator.genThirdException(); } catch (MyThirdException e) { e.printStackTrace(); } } } class ExceptionGenerator { //抛出第一种编译时异常 public void genFirstException() throws MyFirstException { throw new MyFirstException("第一种编译时类型的异常"); } //抛出第二种运行时异常 public void genSecondException() { throw new MySecondException("第二种运行时类型的异常"); } //抛出第二种编译时异常 public void genThirdException() throws MyThirdException { throw new MyThirdException("第三种编译时类型的异常"); } } /* 第一种自定义编译时异常 */ class MyFirstException extends Exception { public MyFirstException(String msg) { super(msg); } } /* 第二种自定义运行时异常 */ class MySecondException extends RuntimeException { public MySecondException(String msg) { super(msg); } } /* 第三种自定义编译时异常 */ class MyThirdException extends Exception { public MyThirdException(String msg) { super(msg); } }