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
Matthew Francis
6,967 PointsNewbie - using "throws"?
I've read you should use "throws" whenever you want to try/catch that error later. But why not do it on the spot?
like this:
public void method(){
try{....method...}
catch(IOException ioe){.......handle it.....}
}
And this is what happens if you use throws:
public void method() throws IOException {...}
public void otherMethod(){
try{...method...}
catch(IOException ioe){....}
}
1 Answer
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsI think there is a misunderstanding. When you have exception that is handled in method, you don't specify throws Exception anymore (unless you re-throw exception, see below):
public void method() { // no throws signature, if after catch you don't throw new one
try {
// code throwing Exception
} catch (Exception ex) {
// handle the exception but not re-throw new one
// for example System.exit();
}
}
In this case later on when you execute otherMethod with method inside you don't care about what is happening inside method, because you took care about it like this. and you know if exception happens, it will be handled, and
all will be good :
public void otherMethod() {
method();
}
There are however situations in Java when you have to re-throw exception. Real world example. You have website with database, uses SQL operations. When error happens on database level you want to generate beautiful error page, saying what went wrong. You have method dealing with database, For Example:
public void methodDoingSqlOperations() throws YourApplicationException {
try {
// code throwing SqlException
} catch (SqlException e) {
// we catch SqlException, but throw our one, because we know how to deal with it
throw new YourApplicationException(SqlException, "some other parameters");
}
}
Now after you caught SqlException and re-throw new YourApplicationException, you have method that generate webpages:
public void methodGeneratingWebPage() throws YourApplicationException {
try {
methodDoingSqlOperations();
} catch (YourApplicationException e) {
// generated friendly error page that something went wrong.
}
}
But coming back to your question. You do not need to re-throw Exceptions over and over again, if you handle them. This is pointless.