Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try/catch versus throws Exception

Tags:

java

exception

People also ask

Which is better throw or try-catch?

From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method.

Does try-catch throw exception?

The try... catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.

What is difference between try and catch?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

What happens if catch block throws exception?

If an exception is thrown inside the catch-block and that exception is not caught, the catch-block is interrupted just like the try-block would have been. When the catch block is finished the program continues with any statements following the catch block.


Yes, there's a huge difference - the latter swallows the exception (showing it, admittedly), whereas the first one will let it propagate. (I'm assuming that showException doesn't rethrow it.)

So if you call the first method and "do something" fails, then the caller will have to handle the exception. If you call the second method and "do something" fails, then the caller won't see an exception at all... which is generally a bad thing, unless showException has genuinely handled the exception, fixed whatever was wrong, and generally made sure that calculateArea has achieved its purpose.

You'll be able to tell this, because you can't call the first method without either catching Exception yourself or declaring that your method might throw it too.


They differ in where the responsibility to deal with the Exception lies. First one just throws Exception, so it does not handle it. The code that calls the method needs to handle the Exception. Second one catches and handles the Exception within the method, so in this case the caller doesn't have to do any exception handling, provided showException() itself does not throw another exception.


Yes. The version which declares throws Exception will require the calling code to handle the exception, while the version which explicitly handles it will not.

i.e., simply:

performCalculation();

vs. moving the burden of handling the exception to the caller:

try {
    performCalculation();
catch (Exception e) {
    // handle exception
}

Yes, there is a great deal of difference between them. The in the first code block, you pass the exception to the calling code. In the second code block you handle it yourself. Which method is correct depends entirely on what you are doing. In some instances, you want your code to handle the exception (if a file isn't found and you want to create it, for instance) but in others, you want the calling code to handle the exception (a file isn't found and they need to specify a new one or create it).

Generally speaking as well, you don't want to catch a generic exception. Instead, you'll want to catch only specific ones, such as FileNotFoundException or IOException because they can mean different things.


There is one particular scenario where we cannot use throws, we have got to use try-catch. There is a rule "An overridden method cannot throw any extra exception other than what its parent class is throwing". If there is any extra exception that should be handled using try-catch. Consider this code snippet. There is a simple base class

package trycatchvsthrows;

public class Base {
    public void show()
    {
        System.out.println("hello from base");
    }
}

and it's derived class:

package trycatchvsthrows;

public class Derived extends Base {

    @Override
    public void show()   {
        // TODO Auto-generated method stub
        super.show();

        Thread thread= new Thread();
        thread.start();
        try {
            thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // thread.sleep(10);
        // here we can not use public void show() throws InterruptedException 
        // not allowed
    }
}

When we have to call thread.sleep() we are forced to use try-catch, here we can not use:

 public void show() throws InterruptedException

because overridden method can not throw extra exceptions.