Package prac_1;/** * <p>title: Catch exceptions and implement your own exception class </p> * <p>description: Implement your own exception class by inheriting the exception class. and use Try-catch to catch this exception. </p> * <p>copyright:copyright (c) 2014</p> * <p>filename: </p> * @author Wanghaitao * @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 {/** *<br> method Description: Use the default constructor in the MyException class */public static void A () throws MyException {S Ystem.out.println ("Throwing myexception from A ()"); throw new MyException ();//Throw exception, End method}/** *<br> Method Description: Use the constructor with information in the MyException class */public static void B () throws Myexcep tion {System.out.println ("throwing MyException from B ()"); throw new MyException ("Error in B ()"); }/** *<br> Method Description: Uses the encoded constructor in 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:)
A little bit every day Java---Inherit the exception class to implement its own exception class