0 votes
179 views
in Java by
How to create custom checked exception in java? Anybody can provide running example with code.

1 Answer

0 votes
by (4.4k points)

Checked Exceptions:- Exceptions that checked at compile time that are called checked exceptions. As per Exception hierarchy all classes that extends Exception class except UncheckedException comes under checked exception.

See the following code to create custom Checked Exception:-

package exceptions;

public class CheckedException extends Exception{

    public CheckedException(String message) {
        this(message, null);
    }
    public CheckedException(String message, Throwable th) {
        super(message,th);
    }  
    public CheckedException(Throwable th) {
        super(th);
    }
}

To use custom Checked Exception in our project:-

package exceptions;

public class TestException {

    public static void main(String[] args) {
            try {
                checkedExceptionTest();
            } catch (CheckedException e) {
                e.printStackTrace();
            }
    }

    private static void checkedExceptionTest() throws CheckedException{
        throw new CheckedException("Checked Exception");
    }

}

Output:-

exceptions.CheckedException: Checked Exception
    at exceptions.TestException.checkedExceptionTest(TestException.java:18)
    at exceptions.TestException.main(TestException.java:11)

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...