java and custom exception throw, throws using

A custom exception class

We know that all exceptions are Exception, so we need to custom exception need only to extend the Exception class on it. Let a custom exception class, as follows:

/ ** 
 * custom exception 
 * / 
// inherited Exception 
public  class MyException   the extends Exception {
     public MyException (String Message) {
         // occurrence of abnormality in the print statement 
        Super (Message); 
    } 
}

 

Second, the design method throws an exception

Now we can design a method throws an exception, as follows:

public  class Student {
                            // display an exception is thrown, you can throw out the more,
                           // then calls this method must continue to throw or catch the exception 
    public  void STU ( int Age) throws MyException, ArithmeticException {
         IF (Age <18 ) {
             the throw  new new MyException ( "handsome, you are not old enough" ); 
        } 
        System.out.println ( "Welcome, sign up!" ); 
    } 
}

 

Note that the format is thrown behind the method throws keyword, you can throw multiple exceptions can be separated by comma. In the program which we ask of age must be greater than 18, otherwise it throws an exception displayed, the keywords used here is throw. We just throw the new exception class objects.

Third, test methods

We call this method in the main method. As we designed this method throws an exception. All the time we call the compiler requires us to handle exceptions. We have two approaches

1, using the try ... catch ... catch the exception

Since the method throws two exceptions so we both need to capture. code show as below:

public class Run {
    public static void main(String[] args) {
        Student student = new Student();
        try {
            student.stu(18);
        } catch (ArithmeticException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

 

2, using the method call throws continue thrown.

We also need to throw two exceptions. Code is as follows: 

public  class the Run {
     public  static  void main (String [] args) throws an ArithmeticException, 
            MyException { 
        Student Student = new new Student (); 
        student.stu ( 18 is ); 
    } 
}

 

Guess you like

Origin www.cnblogs.com/weibanggang/p/11184716.html