Friday, November 15, 2019

Custom Checked/Unchecked Custom Exception

How to create checked/unchecked custom exceptions in Java?
Or
Creating user defined checked exception?
Or
Creating user defined unchecked exception?

There are two types of Exceptions

  • Exception: This is also known as checked exception. 
  • RuntimeException: This is known as unchecked exception.
Creating user defined or custom checked exception.

class CustomCheckedException extends Exception {
 
    CustomCheckedException(String s) {
           super(s);
    }
 
}
We can create custom checked exception by extending java.lang.Exception.


Creating user defined or custom unchecked exception.
class CustomUncheckedException extends RuntimeException {
 
    CustomUncheckedException(String s) {
           super(s);
    }
 }
we can create custom unchecked exception by extending java.lang.RuntimeException.
  Let see the complete example as mention below. How to create and use. 
package com.javaiq.in;
 
/*
 * User defined Custom checked Exception.
 */
class CustomCheckedException extends Exception {
 
    CustomCheckedException(String s) {
           super(s);
    }
 
}

public class CustomCheckedExceptionTest{
    public static void main(String[] arg) {
           try {
                  throw new CustomCheckedException("Handlle CustomCheckedException.");
           } catch (CustomCheckedException e) {
                  e.printStackTrace();
           }
 
    }
}
Output:
com.javaiq.in.CustomCheckedException: Handlle CustomCheckedException.
 at com.javaiq.in.CustomCheckedExceptionTest.main(CustomCheckedExceptionTest.java:17)



Related Posts:

No comments:

Post a Comment