java key mechanism for handling exceptions and throw throws

In the process of exception handling, the distinction between throws and throw that?

throws: method is a method in the statement, without treatment, but to upload, who calls whom treatment.

throw: throw in a specific type of exception.

throws chestnuts:

throws, then, is this approach is likely to cause an exception, but I just will declare it out, I do not deal with, if someone to call, you can know that this approach is likely to throw an exception, if I call, I have processing or subsequently throws.

Format: Method name (parameter) throws an exception type, exception class 2, .....
 1 class Math{
 2       public int div(int i,int j) throws Exception{
 3           int t=i/j;
 4           return t;
 5       }
 6  }
 7 
 8 public class ThrowsDemo {
 9       public static void main(String args[]) throws     Exception{
10           Math m=new Math();
11           System.out.println("出发操作:"+m.div(10,2));
12      }
13  }

throw: In a method of exception can capture may be performed throws

Note throws: Once executed, the program will be immediately transferred to exception handling stage, behind the statement is no longer enforced, and where the method no longer returns meaningful value.

. 1 public  class TestThrow
  2 {
  . 3      public  static  void main (String [] args) 
  . 4      {
  . 5          the try 
 . 6          {
  . 7              // Call a method declared throws, catches the exception must explicitly 
 8              // Otherwise, the main method must again throw statement 
 . 9 throwChecked (-3 );            
 10          }
 . 11          the catch (Exception E)
 12 is          {
 13 is              System.out.println (e.getMessage ());
 14          }
 15         // method call exception may be thrown Runtime explicitly capture the exception, 
16          // may not ignore the exception 
. 17 throwRuntime (. 3 );
 18 is      }
 . 19      public  static  void throwChecked ( int A) throws Exception
 20 is      {
 21 is          IF (A > 0 )
 22          {
 23              // own exception thrown exception 
24              // this code must be in the try block, or in the declared method throws belt 
25              the throw  new new exception ( "a value greater than zero, do not meet the requirement" );
 26          }
 27     }
 28      public  static  void throwRuntime ( int A)
 29      {
 30          IF (A> 0 )
 31 is          {
 32              // Self RuntimeException thrown exception, either explicitly capture the exception 
33              @ may completely ignore the exception, to the the exception to the caller processing method 
34 is              the throw  new new a RuntimeException ( "a value greater than zero, do not meet the requirement" );
 35          }
 36      }
 37}

 

Guess you like

Origin www.cnblogs.com/qingmuchuanqi48/p/10935662.html