要求参数m的值大于1000时,方法抛出一个MyException对象。最后编写主类,在主方法中创建Student对象,让该对象调用speak()方法。
package javase12; public class MyException extends Exception { public MyException(String ErrorMessagr){ super(ErrorMessagr); //super 直接调用父类方法 } }
package javase12; public class Student { public void speak(int m) throws MyException{ if (m>1000){ throw new MyException("参数m大于1000抛出异常错误"); } } }
package javase12; public class Brunt { public static void main(String args[]) { Student u=new Student(); //实例化Student类 try{ u.speak(1500); //调用Student类的m参数为1500 }catch(MyException e){ e.printStackTrace(); //printStackTrace()是异常类的一个方法。 } } }