If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).
The code looks like:
public void someMethode() throws SomeCheckedException {
// code
}
Then later you can deal with the exceptions if you don't wanna deal with them in that method.
To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)
try {
// exceptional block of code ...
// ...
} catch (Exception e){
// Deal with e as you please.
//e may be any type of exception at all.
}
The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').
If you want to handle your own exceptions first simply add a catch block before the generic Exception one.
try{
}catch(MyOwnException me){
}catch(Exception e){
}
Answer from jjnguy on Stack OverflowIf you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).
The code looks like:
public void someMethode() throws SomeCheckedException {
// code
}
Then later you can deal with the exceptions if you don't wanna deal with them in that method.
To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)
try {
// exceptional block of code ...
// ...
} catch (Exception e){
// Deal with e as you please.
//e may be any type of exception at all.
}
The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').
If you want to handle your own exceptions first simply add a catch block before the generic Exception one.
try{
}catch(MyOwnException me){
}catch(Exception e){
}
While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.
try{
// IO code
} catch (Exception e){
if(e instanceof IOException){
// handle this exception type
} else if (e instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
throw e;
}
}
However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable
try{
// IO code
} catch (Throwable t){
if(t instanceof Exception){
if(t instanceof IOException){
// handle this exception type
} else if (t instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else if (t instanceof Error){
if(t instanceof IOError){
// handle this Error
} else if (t instanceof AnotherError){
//handle different Error
} else {
// We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else {
// This should never be reached, unless you have subclassed Throwable for your own purposes.
throw t;
}
}
Videos
It is only good practice to catch a specific exception if it can actually be handled by the catch block.
Very often, programmers assume that the fault can be handled at all, close to the point of occurrence. This is often wrong. To understand why, we need to explore what "handling" means.
Your second snippet:
try {
// code implementation
} catch (IOException | SQLException | NullPointerException ex ) {
// handle exception
}
implies that there could be some useful action which could handle the caught exception. But this is often not so. As was noted in the comments, performance is irrelevant if the code gives incorrect results.
About the only thing you can do with a NullPointerException is to log everything salient for debugging and die; any further attempt to continue has a high probability of stomping on the heap and breaking other things down-stream. This exception results from a software defect and cannot be properly handled at all.
I'll assume the code implementation consists of reading a istream. Handling an IOException could be as simple as re-reading the part that threw the exception (if caused by an interrupted system call) but that's the rare case and an over-generalized exception. If the error is FileNotFoundException, you've got an upstream defect which cannot be handled in this context. Who could handle it? The code which created the istream could have handled the exception if there was a reasonable alternative file to open, but the sample snippet should lack the information. If we were trying to open a file with no reasonable alternate, all the opener can do is throw an exception itself.
Why? Because there is a contract between the opening code and its caller that says "you give me a pathname, and I will open it for you and give you an istream". Upon FileNotFoundException, the opening code has failed to fulfill its contract and will induce failures in the caller and other places where the istream is accessed. It is this violation of contract is the strongest case for exceptions.
Let's assume that the FileNotFoundException was thrown in a long running program like an editor. It would be rude for the application to crash just because you typo'ed a filename. In this case, the exception should be allowed to propagate up to the main loop which actually can handle it: namely by informing the user "file not found" thus giving the user an opportunity to try another filename.
When an Exception implies a contract failure that exception must propagate upwards until there is code that can actually rectify the contract failure. If there is no place that failure can be rectified (as in cat not_a_file) the best you can do is print a meaningful error message and (as in cat not_a_file a_file) skip not_a_file.
I would assume that checking for specific exceptions would have an impact in performance (even if it is minimal) because the program would compare the exception triggered with 3 different values, instead jumping straight to the exception clause. This would increase the number of CPU cycles taken, hence reduce performance.
Listing all exceptions does not improve readability or functionality of the code though, so I would suggest you catch all exceptions by default, unless you need to catch an exact type of an exception.
This has been possible since Java 7. The syntax for a multi-catch block is:
try {
...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
NoSuchFieldException e) {
someCode();
}
Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type.
Also note that you cannot catch both ExceptionA and ExceptionB in the same block if ExceptionB is inherited, either directly or indirectly, from ExceptionA. The compiler will complain:
Alternatives in a multi-catch statement cannot be related by subclassing
Alternative ExceptionB is a subclass of alternative ExceptionA
The fix for this is to only include the ancestor exception in the exception list, as it will also catch exceptions of the descendant type.
Not exactly before Java 7 but, I would do something like this:
Java 6 and before
try {
//.....
} catch (Exception exc) {
if (exc instanceof IllegalArgumentException || exc instanceof SecurityException ||
exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {
someCode();
} else if (exc instanceof RuntimeException) {
throw (RuntimeException) exc;
} else {
throw new RuntimeException(exc);
}
}
Java 7
try {
//.....
} catch ( IllegalArgumentException | SecurityException |
IllegalAccessException| NoSuchFieldException exc) {
someCode();
}
tldr: Throwable catches errors that Exception misses
So I was trying to write a JavaMail web app and my app was not giving me any outputs. No error or success message on the web page, no errors in Tomcat logs, no email at the recipient address. I added a out.println() statement to the servlet code and manually moved it around the page to see how much of it was working. All my code was wrapped in:
try {} catch (Exception) {}Realizing that my code was stopping midway through the try block and the catch block wasn't even triggering, I started googling and found this stackoverflow page. Turns out, Exception class is derived from the Throwable class. Changing my catch(Exception e) to catch(Throwable e) and recompiling the project worked. The webpage printed a stacktrace for the error and I was able to resolve it.