Forums Register Login

An "exceptional" error

+Pie Number of slices to send: Send
I've just started learning about exceptions ( try/catch and throwing exceptions ). Here is a small program I wrote trying to understand the relationship between throwing exceptions and try/catch.



Note that I am trying to obtain the exceptions. What I'm confused about is how java handles these exceptions. So far, I understand that if I "throw" an exception, it will be caught by the method that called it. Now I have various "catch" statements in my code, if I "catch" the exceptions, then will the exceptions not be passed on?

Example, methodC() is supposed to throw an ArithmeticException, but I have a "catch" statement in the body of the method, then is the exception caught? In other words, will methodB() never have an exception error because it's not possible since all exception errors were already dealt with in methodC()?
+Pie Number of slices to send: Send
A thrown exception will be caught by whatever catch clause exists to catch it; whether it's in the your current method or the method that called it doesn't matter, for example:



This will simply print the message.

In your code:



The exception is caught immediately, you print a message and then the stack trace, and the Java program happily executes the rest of itself, whatever it may be - the exception has been handled and will not be passed on to anything UNLESS you re-throw it:



Note that I just added "throw ex;" to the catch block. So in your case, methodB and methodA will never catch the exception from method C because you've already handled it right away (try removing the catch clause from your methodC, then from methodB, and finally from methodA!).
+Pie Number of slices to send: Send
You can confuse yourself because ArithmeticException is unchecked. That means you can write throws ArithmeticException on every method you have got, and the compiler will ignore it. If you wrote throws InterruptedException, however, you would get a compiler error that "interruptedException is never thrown ..."
Your try-catch blocks means that none of your methods ever throws an Exception at all. Unless you try ted Smyth's alteration, that is.
Everyone is a villain in someone else's story. Especially this devious tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 932 times.
Similar Threads
Is finally, really finally
Exeption Handling
OOP-2 : NaturalLanguageMultiply
Jane's study notes about exception handling
try/catch question
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 18:33:35.