Java-- 异常(2)
晚上打雷了,鉴于前天打雷吧路由器和猫都弄坏了,今天就不写解释了。直接上代码。
主要是自定义异常的使用,通过System.err而将错误发送给标准错误流。通常这比把错误的信息输出到System.out要好,因为System.out也许会被重定向。
如果把结果送到System.err,它就不会随System.out一起被重定向,这样更容易被用户注意。
也可以以为异常类定义一个接受字符串参数的构造器。
1 package com.exceptions; 2 3 4 class MyException extends Exception{ 5 public MyException(){ 6 } 7 public MyException(String msg){ super(msg);} 8 } 9 10 public class FullConstructors { 11 public static void f() throws MyException{ 12 System.out.println("Throwing MyException from f()"); 13 throw new MyException(); 14 } 15 16 public static void g() throws MyException{ 17 System.out.println("Throwing MyException fron g()"); 18 throw new MyException("Originated in g()"); 19 } 20 21 public static void main(String[] args){ 22 try{ 23 f(); 24 }catch(MyException e){ 25 e.printStackTrace(System.out); 26 } 27 try{ 28 g(); 29 }catch(MyException e) 30 { 31 e.printStackTrace(System.out); 32 } 33 } 34 }
结果:
1 Throwing MyException from f() 2 com.exceptions.MyException 3 at com.exceptions.FullConstructors.f(FullConstructors.java:13) 4 at com.exceptions.FullConstructors.main(FullConstructors.java:23) 5 Throwing MyException fron g() 6 com.exceptions.MyException: Originated in g() 7 at com.exceptions.FullConstructors.g(FullConstructors.java:18) 8 at com.exceptions.FullConstructors.main(FullConstructors.java:28)