Exception thrown inside catch block - will it be caught again?
No, since the new throw
is not in the try
block directly.
Throwing same exception inside catch block
The finally
block should always execute. This is the main reason. The exception is thrown in the catch
block but return
statement executed in the finally
block masks exception. Either remove finally
block or move return
statement out of the finally
block.
Will exception thrown in catch block be caught by later catch blocks?
No. Only exceptions thrown in the associated try
block may be caught by a catch
block.
How to throw an Exception inside a Try/Catch block?
Checked vs Unchecked Exceptions
It's totally acceptable to throw an exception in a catch block. A common use case is to take a checked Exception
and throw a unchecked RuntimeException
which would allow the exception bubble up to where it needs to be handled.
You'll want to use checked exceptions for use cases such as Connectivity/IO, SQL exceptions..
Handling Checked Exceptions
To answer your question, in most libraries that connect to the database, an checked IOException
is thrown if there are any connectivity issues. For these cases, you can always specify this in the method signature public Class createClass() throws IOException
this specifies that any callers of createClass()
has to fulfill the contract that the IOException
is handled.
or
You can rethrow this as a RuntimeException
try {
...
} catch (IOException e) {
throw new RuntimeException(e); // <- send the original exception so you can preserve the exception and stacktrace.
}
This will essentially bubble up to STDOUT or whatever handler your framework specifies.
CAUTION:
However, catching an cover all Exception
and throwing a more specific ClassIOException
can have unintended consequences.
If you have a NullPointerException
this will be captured by your catch (Exception e)
block and rethrown as a ClassIOException
Doing this will corrupt the stacktrace and cause your error logs to be much more difficult to debug.
Understanding what constitutes an checked Exceptions.
Another tip is to consider what your Exception
cases are.
If they are standard flow of the application, service, or business logic -- these may not be appropriate exceptions.
The ClassAlreadyRegisteredException
and ProfessorNotFoundException
may not be exceptional cases in your application... unless these are already specified by your professor.
Sometimes these can be thrown as RuntimeException
if the situation calls for it.
Best Practices?
There are still many opinions on how exceptions are handled. So here are some rule of thumb questions I ask myself when working with exceptions
- Is the stacktrace preserved? Will I be able to trace back to the root Exception
- Is this common logic and represents an exceptional case that deviates from what my application provides?
- If I throw this exception, is it an absolute necessity for anything calling this method to handle this exceptional logic?
Re-throw an exception inside catch block
The rethrown exception can have a different type.
This compiles and runs correctly on VS2012:
#include <iostream>
int main() try
{
try
{
throw 20;
}
catch (int e)
{
std::cout << "An exception occurred. Exception Nr. " << e << std::endl;
throw std::string("abc");
}
}
catch (std::string const & ex)
{
std::cout << "Rethrow different type (string): " << ex << std::endl;
}
Output:
An exception occurred. Exception Nr. 20
Rethrow different type (string): abc
If we always put Exception object in catch block, then finally bock is never needed?
Are there some circumstances where
finally
block is needed?
Yes there are:
The
finally
block is also executed in the event of areturn
,continue
orbreak
that ends thetry
block, an exception thrown in thecatch
block, and so on.There are exceptions that won't be caught by
catch (Exception e) {
. (And that you shouldn't catch them. They areError
and its subclasses.)
(Just about the only thing that won't run the code in a finally
block is an action that causes the JVM to exit.)
Note that you shouldn't write code like that anyway. It is usually a bad idea to try to handle Exception
, because it is typically too difficult to figure out all of the possible exceptions that could occur ... and hence what to do about it. (Printing a stacktrace and continuing is rarely the correct thing to do!)
That means the idea of "handling all of the exceptions" instead of a finally
is typically impractical.
Exception thrown in catch and finally clause
Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:
When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.
Note that applicable catch or finally blocks includes:
When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.
Now retrace the execution remembering that, whenever you hit throw
, you should abort tracing the current exception and start tracing the new exception.
PHP unable to caught exception thrown inside catch
The catch
blocks only catch exceptions coming from the try
block.
If you need to catch exceptions thrown from any of the catch
blocks you have to wrap the inner code in another try-catch
structure:
try {
throw new FIRST("FIRST", 1);
} catch(FIRST $e) {
//caught
try {
if(sth) {
echo 'ok'; //printed
throw new SECOND("SECOND", 1);
echo 'ok'; //never printed
}
} catch (SECOND $e) {
//caught
}
}
catch(SECOND $e) {
//not caught
}
catch(PDOException $e) {
//caught
}
finally {
//
}
Related Topics
Jdbc Connection to Mssql Server in Windows Authentication Mode
Java.Util.Concurrentmodificationexception Not Thrown When Expected
Get Declared Fields of Java.Lang.Reflect.Fields in Jdk12
How to Tell Jackson to Ignore a Property for Which I Don't Have Control Over the Source Code
Simpledateformat Parse(String Str) Doesn't Throw an Exception When Str = 2011/12/12Aaaaaaaaa
How to Capture Global Key Presses in Java
How to Solve the 'Classic' Knapsack Algorithm Recursively
Performance of Javafx Gui VS Swing
Refreshing Gui by Another Thread in Java (Swing)
Apache Httpclient Interim Error: Nohttpresponseexception
Java String - See If a String Contains Only Numbers and Not Letters
Why Can't You Have Multiple Interfaces in a Bounded Wildcard Generic
Calling a @Bean Annotated Method in Spring Java Configuration