Tuesday, 6 March 2018

Custom Uncecked Exception in Java

We can create the custom Unchecked exception by extending the RunTimeException class as follow. Here We are throwing runtime exception if list is empty.

package com.sample.java.testing;

public class CustomRunTimeException  extends RuntimeException{
   
    public CustomRunTimeException(String message)
    {
        super(message);
    }
   
    public CustomRunTimeException(String message, Throwable throwable){
        super(message, throwable);
    }
   

}


package com.sample.java.testing;

import java.util.ArrayList;

public class CustomRuntimeExceptionDemo {
   
    public String proceedWithOrder(ArrayList<String> arrayList){
       
        if(arrayList.size() > 0){
            return "proceed";
        }else{
            throw new CustomRunTimeException("List is Empty to Proceed");
        }
       
    }

    public static void main(String[] args) {
       
        ArrayList<String> arrayList = new ArrayList<String>();

        CustomRuntimeExceptionDemo customRuntimeExceptionDemo = new CustomRuntimeExceptionDemo();
        customRuntimeExceptionDemo.proceedWithOrder(arrayList);
    }

}

Output :

Exception in thread "main" com.sample.java.testing.CustomRunTimeException: List is Empty to Proceed
    at com.sample.java.testing.CustomRuntimeExceptionDemo.proceedWithOrder(CustomRuntimeExceptionDemo.java:12)
    at com.sample.java.testing.CustomRuntimeExceptionDemo.main(CustomRuntimeExceptionDemo.java:22)
 

No comments:

Post a Comment