throw 抛出异常
throws抛出异常声明
首先自定义异常类(继承Exception类)
public class MyException extends Exception {public MyException(String message){super(message);}}
抛出异常
package yh;public class Test {public void g(int num) throws MyException{if(num < 0)throw new MyException("参数不能为负!");elseSystem.out.println(num);} public static void main(String[] args) {// TODO Auto-generated method stubTest t = new Test();try{t.g(1); t.g(2);t.g(-1);t.g(5);}catch(MyException e){System.out.println(e.getMessage());}}}
输出结果如下: