Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

An "exceptional" error

 
Edward ku
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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()?
 
Ted Smyth
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!).
 
Campbell Ritchie
Sheriff
Pie
Posts: 50211
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic