继承Exception类
public class MyFirstException extends Exception{ public MyFirstException(){ } public MyFirstException(String msg){ super(msg); } public MyFirstException(String msg,Throwable cause){ super(msg,cause); } public MyFirstException(Throwable cause){ super(cause); } }
继承Throwable类
public class MySecondException extends Throwable{ public MySecondException(){ } public MySecondException(String msg){ super(msg); } public MySecondException(String msg,Throwable cause){ super(msg,cause); } public MySecondException(Throwable cause){ super(cause); } }
插曲:
方法里中有throw的时候,方法名一定要有throws抛出异常
果然第一行抛出异常后就停止了,第二行TestOneTwoException.secondException()没有执行
回来:
1.要有自己定义的异常类
2.要有方法抛出了这个异常,下面的firstException()和secondException()
3.有调用这个方法TestOneTwoException.firstException()
public class TestOneTwoException { public static void firstException() throws MyFirstException{ throw new MyFirstException("First异常"); } public static void secondException() throws MySecondException{ throw new MySecondException("Second异常"); } public static void main(String[] args) { try { TestOneTwoException.firstException(); } catch (MyFirstException e) { // TODO: handle exception System.out.println("11111"+e); } try { TestOneTwoException.secondException(); }catch(MySecondException e){ System.out.println("22222"+e); } } }
时间: 2024-12-27 08:36:01