PM_ME_PUZZLES
PM_ME_PUZZLES

Reputation: 11

What is the meaning of this statement from a blog saying a function has to declare Throwable at method signature to catch it?

I am trying to understand exception handling in Java and i keep running into variations of the below mentioned confusing statement in several articles -

There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.

This is from http://javarevisited.blogspot.com/2014/02/why-catching-throwable-or-error-is-bad.html#ixzz4hQPkFktf

However, this code compiles -

class CatchThrowable
{

    void function()
    {

        try
        {
            throw new Throwable();
        }
        catch (Throwable t)
        {

        }
    }

    public static void main(String[] args)
    {

        try
        {

        }
        catch (Throwable t)
        {

        }
    }
}

Both main and function are able to catch Throwable without declaring that they throw it. My understanding is that the throws keyword is used to declare the checked exceptions which a function throws, not those which it catches. Please clarify the quoted statement.

Upvotes: 1

Views: 63

Answers (1)

guenhter
guenhter

Reputation: 12177

The statement:

order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.

is basically wrong.

You just have to understand the following. There is a exception Hierarchy enter image description here A method can throw all types of exception, it just depends on your needs which one you catch and which one not.

It is also not a good idea to catch Error (which includes that you should also not catch Throwable) because there are some severe JMV-VirtualMachineError's like OutOfMemoryError which you usually not should catch.

But this has nothing to do which the fact, what a method declares in its throws part.

Upvotes: 1

Related Questions