正在加载图片...
hapter 9: Error Handling with Except public void f() throws SimpleException t System. out. println("Throw SimpleException fre throw new SimpleException()i public static void main(String[] args)t SimpleR SimpleExceptionDemo ()i try t sed. f(i 1 catch(SimpleException e)i System. err println("Caught it!") monitor. expect(new string[] i Throw SimpleException from f()", "Caught it! }); 编译器创建了一个默认的构造函数,它会自动地(并且用一种你看不到的 方式)调用基类的默认构造函数。当然,在这个例子中 Simple Exception( String)的构造函数就没有了,但实际上它用的也 不多。正如你将看到的,对异常来说,最重要的是这个类的名字,所以绝 大多数时候这个异常也就够用了。 这里,会用 Systen.err把结果打印到控制台的标准错误流( standarc eror)。对于错误信息来说,送到这里通常会比送到 System.out要 好,因为后者可能会被重定向。如果你将输出送到 System.err,那么 即使是在 System. out被重定向的时候,它还是会被打印在屏幕上的, 这样就能更好地引起用户的注意。 你也可以在你创建的的异常类里定义以 String作参数的构造函数。 //: C09: FullConstructors java import com. bruceeckel simpletest* class My Exception extends Exception t public My Exception()(I public My Exception(String msg)( super(msg)i 1 public class Fullconstructors t private static Test monitor new Test()i public static void f() throws MyException i System. out. println("Throwing MyException from throw new My Exception ()i public static void g( throws MyException System. out. println("Throwing MyException from throw new My Exception("Originated in g(")i 第6页共6页 www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.comChapter 9: Error Handling with Exceptions www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com ✞ 6 ✟ ✠ 6 ✟ public void f() throws SimpleException { System.out.println("Throw SimpleException from f()"); throw new SimpleException(); } public static void main(String[] args) { SimpleExceptionDemo sed = new SimpleExceptionDemo(); try { sed.f(); } catch(SimpleException e) { System.err.println("Caught it!"); } monitor.expect(new String[] { "Throw SimpleException from f()", "Caught it!" }); } } ///:~ !1Îb…^\|stuQ#9~•ð(i¬^?± @A)º|stuQFx#R\6N! Sim pleException( String)stuQ À-…#+­ãg9$ [P¶±D#÷èZ`a#;R\#,S¤ Ï[Q"R\èZ$ G… R#~ System . err ·ñòó2ôvyõ(standard error)÷kGH`a#öR<Z~ö System . ou t ; #Æyjž'~/e÷¶·±Dø„ö System . err#K‡ 4Ž System . ou t /e÷"#9³~/ñòßùg# RO 'óCµúÆâ ±$žS±ÎbèZe:S String »‚QstuQ //: c09:FullConstructors.java import com.bruceeckel.simpletest.*; class MyException extends Exception { public MyException() {} public MyException(String msg) { super(msg); } } public class FullConstructors { private static Test monitor = new Test(); public static void f() throws MyException { System.out.println("Throwing MyException from f()"); throw new MyException(); } public static void g() throws MyException { System.out.println("Throwing MyException from g()"); throw new MyException("Originated in g()");
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有