正在加载图片...
Thinking in Java 3 Edition 此外你还可以用 Throwable的基类,也就是 Object(所有对象的基类) 的方法。对异常来说有一个很有用的方法, getclass()。它会返回一个 “表示这个对象是属于哪种类型的” class对象。接下来,你可以用 getName()查询这个 Class对象的名字。你还可以用 Class对象作 更复杂的事情,不过对异常处理来说,就没这个必要了 下面这段程序演示了这些基本的 Exception方法的用法 //: c09: ExceptionMethods java / Demonstrating the Exception Methods import com. bruceeckel simpletest*i public class ExceptionMethods t private static Test monitor new Test() public static void main(String[] args) i ception("My Exe 1 catch(Exception e)t println (" Caught e getMessage() e get LocalizedMessage()ig System. err println("getLocali mEssage(): stem.err println("print stackTrace():")i e print stackTrace()i String[] t Caught Exception getMessage () My Exception" tostring () java. lang Except My Exception "printstackTrace(): 号号\ tat ExceptionMethods,main\(.*\)” 你能看到这些方法一个比一个提供更多的信息—实际上它们每个都是前 个的超集 重抛异常 有时你需要重新抛出那个刚捕捉到的,用 Exception捕捉到的异常。由 于你已经有了当前异常的 reference,因此你可以直接将那个 reference 重抛出来 System. err println("An exception was thrown") 第11页共11页 www.wgqqh.com/shhgs/tij.htmlThinking in Java 3 rd Edition ✞ 11 ✟ ✠ 11 ✟ www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com š±³žS Th rowable #$  Object(,-÷`) @n÷èZ`a-^\ä-@n#getCl ass( )9~op^\ øùR\÷`jkã?ÐCl ass ÷`|`#±žS getN am e( )¨1R\ Cl ass ÷`±³žS Cl ass ÷`» ói2¢ #=÷èZ78`a# ÀR\;… R¨%&3ù…R2 Exception @nnÊ //: c09:ExceptionMethods.java // Demonstrating the Exception Methods. import com.bruceeckel.simpletest.*; public class ExceptionMethods { private static Test monitor = new Test(); public static void main(String[] args) { try { throw new Exception("My Exception"); } catch(Exception e) { System.err.println("Caught Exception"); System.err.println("getMessage():" + e.getMessage()); System.err.println("getLocalizedMessage():" + e.getLocalizedMessage()); System.err.println("toString():" + e); System.err.println("printStackTrace():"); e.printStackTrace(); } monitor.expect(new String[] { "Caught Exception", "getMessage():My Exception", "getLocalizedMessage():My Exception", "toString():java.lang.Exception: My Exception", "printStackTrace():", "java.lang.Exception: My Exception", "%% \tat ExceptionMethods.main\\(.*\\)" }); } } ///:~ ±'R2@n^\^\†;ó[GHšš­ãg9:¸\.* ^\4   -±;ÔL„K\5# Exception èZ k±ËÌ-…F*èZ referen ce#Ɓ±žSÇ|DK\ referen ce L„`Ê catch(Exception e) { System.err.println("An exception was thrown"); throw e; }
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有