每天一点儿java---继承exception类来实现自己的异常类

每天一点儿java---继承exception类来实现自己的异常类_第1张图片

package prac_1;

/**
 * 

Title: 捕获异常和实现自己的异常类

*

Description: 通过继承Exception类来实现自己的异常类。并使用try-catch来捕获这个异常。

*

Copyright: Copyright (c) 2014

*

Filename:

* @author 王海涛 * @version 0.1 */ class MyException extends Exception { public MyException() {} public MyException(String msg) { super(msg); } public MyException(String msg, int x) { super(msg); i = x; } public int val() { return i; } private int i; } public class ExceptionDemo { /** *
方法说明:使用MyException类中默认的构造器 */ public static void a() throws MyException { System.out.println( "Throwing MyException from a()"); throw new MyException();//抛出异常,结束方法 } /** *
方法说明:使用MyException类中带信息的构造器 */ public static void b() throws MyException { System.out.println( "Throwing MyException from b()"); throw new MyException("error in b ()"); } /** *
方法说明:使用了MyException中有编码的构造器 */ public static void c() throws MyException { System.out.println( "Throwing MyException from c()"); throw new MyException( "error in c()", 404); } public static void main(String[] args) { try { a(); } catch(MyException e) { System.out.println( "Error="+e.getMessage()); } try { b(); } catch(MyException e) { System.out.println( "Error="+e.getMessage()); //e.toString(); } try { c(); } catch(MyException e) { System.out.println( "Error="+e.getMessage()); e.printStackTrace(); System.out.println("error code: " + e.val()); } } } //end :)


你可能感兴趣的:(JAVA)