9.3.1 自定义异常类设计
自定义异常一般要提供构造方法和toString()方法class MyException extends Exception{String id;public MyException(String str){id=str;}public String toString() {return "我是异常:"+id;}}
9.3.2 抛出异常
- 系统定义的运行异常由系统在运行程序过程中自动抛出;
- 用户设计的异常,要通过throw语句抛出。
public class TestException {public static void main(String a[]) {try {throw new MyException("一个测试异常");} catch (MyException e) {System.out.println(e);}}}
9.3.3 方法的异常声明
方法中异常抛出的方式:
(1)在方法内对异常进行捕获处理;
(2)将异常处理交给外部调用程序:在方法头使用throws子句列出该方法可能产生哪些异常。
throw语句和throws子句的差异性
返回类型 方法名(参数列表) throws 异常类名列表 { //出现在方法头
…
throw 异常类名 //出现在方法内
…
}
```java (1)对异常捕获处理: public static void main(String a[]) { try{ char c = (char) System.in.read() ;
System.out.println(“你输入的字符是:”+ c);
}catch(java.io.IOException e){ } }
(2)方法头throws列出可能产生哪些异常。
public static void main(String a[]) throws IOException {
char c = (char) System.in.read() ; //存在异常
System.out.println(“你输入的字符是:”+ c);
}
<a name="IlAYk"></a>#### 没在程序中消化掉的异常,虚拟机将在控制台显示。在调用带异常的方法时1. **调用者处理异常---消化掉(try –catch –finally);**try{<br />System.in.read(); <br /> } catch …2. **调用者不处理,在调用者的方法头声明异常(throws ...)。**public static void main(String a[]) throws IOException { <br />char c = (char) System.in.read() ; <br /> ….<br />}3. 没消化的异常被虚拟机收到,则在控制台显示错误。- **方法覆盖时,子类方法的throws子句中异常不能超出父类的范围。**- **子类方法也可不抛出异常。**- **若父类方法没有异常声明,子类的覆盖方法也不能有异常。**class E1 extends Exception { }<br />class E2 extends E1 { }<br />class TestParent { <br /> public void fun(boolean f) throws E1 { }<br />}<br />public class Test extends TestParent { <br /> //---X— <br />}<br />下面哪些方法可以放在—X—位置并通过编译。<br />A. public void fun(boolean f) throws E1 { }<br />B. public void fun(boolean f) { }<br />C. public void fun(boolean f) throws E2 { }<br />D. public void fun(boolean f) throws E1,E2 { }<br />E. public void fun(boolean f) throws Exception { }```javaclass FindRoot{static double[] root(double a, double b, double c)throws IllegalArgumentException {double x[]=new double[2];if (a== 0) {throw new IllegalArgumentException("a 不能为零."); 系统异常类}else {double disc = b*b - 4*a*c;if (disc < 0) 异常是有条件产生throw new IllegalArgumentException("无实数解!");x[0]=(-b + Math.sqrt(disc)) / (2*a);x[1]=(-b - Math.sqrt(disc)) / (2*a);return x;}}public static void main(String arg[]) {try {double x[] = root(2.0,5,3);System.out.println("方程根为:"+x[0]+","+x[1]);}catch(Exception e) { System.out.println(e); }}}
public class Test {public static void main(String[] args) {try { method();}catch(Exception e) {System.out.println("*");}}static void method() {try { wrench();System.out.println("a");}catch(ArithmeticException e) {//换成catch(NullPointerException e)System.out.println("b");}finally {System.out.println("c");}System.out.println("d");}static void wrench()throws NullPointerException {throw new NullPointerException();}}运行结果:c*换成catch(NullPointerException e)后运行结果:bcd
