Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call stack: catch vs. throws

Tags:

java

exception

When to use "catch" and when to use "throws"?

try {
    //stuff
} 
catch (MyException me) {
    //stuff
}

versus

public void doSomething() throws MyException {
    //stuff
}

In the case of "throws", where to place my catch along the call stack?

Main
    ----- Function 1
        ----- Function 2
            ----- Function 3 (generate exception)

If I propagate the exception from function 3 to function 2, why shouldn't function 2 do the same? So at the end I would end up managing all the exceptions in the "main" and I think it's not a go0d practice to put all the code inside a try block, isn't it?

So what's the logical way to choose between "catch" and "throws"? And in the second case, where should I place my catch in the call stack?

like image 557
user1883212 Avatar asked May 25 '26 09:05

user1883212


1 Answers

They're basically inverse of each other. throws means that a function is allowed to throw an exception; catch means that a block (the try) block expects that an exception might get thrown, and is prepared to handle it.

To take the ball metaphor, a pitcher throws an exception that the catcher expects. The catcher catches the ball and handles it somehow. (Well, maybe the metaphor is a bit off, since the catcher usually handles the ball by throwing it back to the pitcher. :) ) Here, the pitcher is a method, and the catcher is a try-catch-[finally] block.

like image 74
yshavit Avatar answered May 27 '26 00:05

yshavit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!