aspose file tools*
The moose likes Beginning Java and the fly likes An Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "An "exceptional" error" Watch "An "exceptional" error" New topic
Author

An "exceptional" error

Edward ku
Greenhorn

Joined: Sep 06, 2011
Posts: 1
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

Joined: May 28, 2008
Posts: 73
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!).


Edward Smith
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39415
    
  28
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: An "exceptional" error