Use throw and throws an exception is thrown

1.throw used in the method throws an exception, it may generally be used on their own exception handling try catch

If you do not handle their own words, it is necessary to use the method throws an exception is thrown in

. 1    public  static  void testAge () {
 2          System.out.println ( "Please enter Age:" );
 . 3          Scanner INPUT = new new Scanner (the System.in);
 . 4          int Age = input.nextInt ();
 . 5          the try {
 . 6              IF (Age <18 || Age> 80 ) {
 7                  the throw  new new Exception ( "about 18 years old, over 80 years of age must be accompanied by guest" );
 8              } the else {
 9                  System.out.println ( "Welcome to the hotel" ) ;
 10              }
 . 11          } the catch(Exception E) {
 12 is              log.error ( "Age abnormality" );
 13          }
 14      } 


to call a method of treating

static void main public (String [] args) { 
the try {
testAge ();
} the catch (Exception E) {
e.printStackTrace ();
log.error ( "Age Exception");
}
}
public static void testAge () throws Exception {
System.out.println ( "Please enter Age:");
Scanner Scanner new new iNPUT = (the System.in);
int input.nextInt Age = ();
IF (Age <18 is || Age> 80) {
the throw new new Exception ( "about 18 years old, over 80 years of age must be accompanied by guest");
} the else {
System.out.println ( "Welcome to the hotel");
}
}


Runtime exception is thrown
different field throwing runtime, does not require treatment, but the program or interrupt the running
static void testAge public () { 
System.out.println ( "Please enter Age:");
Scanner Scanner new new INPUT = (the System.in);. 1
int input.nextInt Age = ();
IF (Age <18 is Age || > 80) {
the throw new new RuntimeException ( "about 18 years old, over 80 years of age must be accompanied by guest");
} the else {
System.out.println ( "Welcome to the hotel");
}
System.out.println ( "Iver ");
}
 

 

Guess you like

Origin www.cnblogs.com/duan2/p/11778471.html