Saturday, August 10, 2013

Java: Checked Exception in detail with examples

Current post is to help one understand checked exceptions with examples. Why it was introduced? How much it is useful?

Checked Exception:


Checked exceptions are those exceptions which are derived from Throwable but not from Error or RuntimeException class & their subclasses.

It means any exception class you derive which is neither from Error nor from RuntimeException class & their subclasses is checked exception class.

You may derive from Throwable Class or Exception Class. It's at user's design discretion.

Checked exceptions must fulfill the Catch-or-Specify rule.


Catch-or-Specify:


Catch-or-Specify rule means that the exception should either be caught via exception handling code or should be specified in method declaration.

Catch - The method should enclose the method which might throw checked exception in try-catch block.

Specify - The method should mention the exception name via 'throws' in its declaration which uses the method which might throw checked exception.


Examples:


Example 1: New Checked Exception class which is derived from Exception Class

Exception Class:

    class MyCheckedException extends Exception
    {
        MyCheckedException()
        {
            super("New Checked Exception");
        }

        MyCheckedException(String msg, Throwable e)
        {
            super(msg,e);
        }
    }

Method that throws MyCheckedException:

    void myMethodThrowsMyCheckedException()
    {
        throw new MyCheckedException();
    }

Usage:

    void somemethod()
    {
        myMethodThrowsMyCheckedException();
    }

For above code you will get similar error depending on IDE:

"...: Must be caught or declared to be thrown"

Do the following to remove compile error:

Method that throws MyCheckedException:

void myMethodThrowsMyCheckedException() throws MyCheckedException
    {
        throw new MyCheckedException();
    }

Usage:

    void somemethod()
    {
        try
        {
            myMethodThrowsMyCheckedException();
        }
        catch(MyCheckedException e)
        {
            //Do the needful :)
        }
    }


Example 2: New Checked Exception class which is derived from Throwable Class

Exception Class:

    class MySecondCheckedException extends Throwable
    {
        MySecondCheckedException()
        {
            super("New Checked Exception from Throwable");
        }

        MySecondCheckedException(String msg, Throwable e)
        {
            super(msg,e);
        }
    }

The method that throws MySecondCheckedException & usage will be similar to above code except for the exception name will be 'MySecondCheckedException'

Why it was introduced?:


As we have seen Checked exception must comply Catch-or-Specify paradigm. And if we fail to catch or specify, compiler shows an error

It is for this reason, checked exception were introduced to have strong exception handling code. It is far better to get error at compile time rather then at runtime on field

How much it is useful?:


It is very useful as one will get an error at compile time if one tries to use your method which might throw checked exception which is neither caught or specified.

Planning to create a helper library with custom exceptions. Checked exception is worth a thought.


Some developers see it as an overhead but for me its a good concept that helps in stable code with good exception handling logic.

Appreciate your feedback via comments.

Thanks,
Mehul
Disclaimer:

The above post and all the posts in the blog are derived from facts, information, logical interpretation and logical conclusion of printed and internet materials available to me, perceived and produced by 99 gm brain of mine, which by no means always be accurate, consistent and complete.

All the posts are for personal quick reference only.

If any suggestion, correction, misinterpretation, misconception commented, which will be moderated and deleted if required, to avoid unforeseen issues.

If any trademark / copywrite issue is present, do send in a mail and appropriate tag (logo, name, website link) will be attached to the same.

Additional disclaimer will be attached wherever required in the post.