throw、throws、rethrow自定义异常类

In Java exception handling:

  •  throw keyword is used to explicitly throw an exception from a method or constructor.
  • throws keyword is used declare the list of exceptions which may be thrown by that method or constructor.

exception包括unchecked exception、checked exception。

一、throw、throws

throw语法:
throw 

throws语法:
type method_name(parameter_list) throws exception_list
{
  // definition of method
}

情况1.throw unchecked exception

If we throw an unchecked exception from a method, it is not mandatory to handle the exception or declare in throws clause. 

public class JavaExample 
{
    public static void main(String[] args) 
    {
        method();
    }
     
    public static void method( ) {
        throw new NullPointerException();
    }
}

情况1.throw checked exception

 if we throw a checked exception using throw statement, we MUST either handle the exception in catch block or method much explicitly declare it using throws declaration.

public class JavaExample 
{
    public static void main(String[] args) 
    {
        try
        {
            method();
        } 
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }
    }
     
    public static void method( ) throws FileNotFoundException 
    {
        throw new FileNotFoundException();
    }
}

二、re-throw

Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

Because the exception has already been caught at the scope in which the rethrow expression occurs, it is rethrown out to the next enclosing try block. Therefore, it cannot be handled by catch blocks at the scope in which the rethrow expression occurred. Any catch blocks for the enclosing try block have an opportunity to catch the exception.

 public  int cat()
    {
       int i=0;
      try{
          i=1/0;
      }catch (ArithmeticException e)
      {
          throw e;
      }
       return 2;
    }
    public static  void main(String[] args) {
        Test t=new Test();
       try {
           int i=t.cat();
           System.out.println(i);
        }catch (ArithmeticException e)
        {
            System.out.println("m");
        }
    }

三、Difference between throw and throws 

throw、throws、rethrow自定义异常类_第1张图片

四、自定义异常类

1.why need for Custom Exception

  • Business logic exceptions – Exceptions that are specific to the business logic and workflow. These help the application users or the developers understand what the exact problem is(按照逻辑自定义异常类)
  • To catch and provide specific treatment to a subset of existing Java exceptions (对异常自定义处理)

2.How to create a custom exception

  • Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones.(依据传统类名以Exception 结尾)
  • Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.(继承Exception 或其子类)
  • Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message.(创建带参构造函数)
class InvalidAgeException extends Exception{  
 InvalidAgeException(String s){  
  super(s);  
 }  
}  
class TestCustomException1{  
  
   static void validate(int age)throws InvalidAgeException{  
     if(age<18)  
      throw new InvalidAgeException("not valid");  
     else  
      System.out.println("welcome to vote");  
   }  
     
   public static void main(String args[]){  
      try{  
      validate(13);  
      }catch(Exception m){System.out.println("Exception occured: "+m);}  
  
      System.out.println("rest of the code...");  
  }  
}  

 

参考:https://howtodoinjava.com/java/exception-handling/throw-vs-throws/

你可能感兴趣的:(Java进阶)