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 <exception_instance>

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 

四、自定义异常类

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值