Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Richard Duffy
16,488 PointsHow to catch exceptions in Java.
How do you catch exceptions in java that are thrown from methods?
3 Answers

Ryan Ruscett
23,309 PointsHey,
When a method throws an exception. It's throwing to to the calling method. That calling method needs to catch it, throw it again and or do nothing with it, which makes troubleshooting hard.
Let's take your method for example. The one that throws an IOException. If this method fails to work, it's going to produce an error. Let's say it fails.
public void doSomething() throws IOException {
//code goes here
}
Let's call that method and catch the IOExecption.
public void catchError() {
try {
doSomething();
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
What happens is that I call doSomething(), which throws an error if it fails. catchError is calling doSomething, so I need to catch the error thrown from doSomething inside my catchError method.
Now, the catch I used a generic example of printing out the output given to the catchError when doSomething throws it back. But where this really comes in handy, is with custom exceptions. Or I can pretty much do anything I want in the catch block. I can say (Hey, I called doSomething, so whatever failed is inisde the method(go write a unit test)). I can say something like that.
Does this help explain it better? Let me know and if not I can try another way.
Thanks!

Richard Duffy
16,488 PointsHey,
I have forgotten how to do this. I am wondering how you catch Exceptions that are thrown by a java method, below is some example code just to drive home my question:
public void doSomething() throws IOException {
//code goes here
}
What I am wondering is how you catch the exception that has been thrown. Thanks for any help.
Regards,
Richard.

Richard Duffy
16,488 PointsHey,
Thanks, it has brought it all back to me.
Regards,
Richard.