exception handling and (throw ex) - exception

What is the best way to handle an exception?
Also, why should I never write:
catch (Exception ex) { throw ex; }

The best way to handle an exception is to do something meaningful in the catch block (the one which in your example contains throw ex). The definition of "meaningful" completely depends on your needs.
You should not do catch (Exception ex) { throw ex; } because that brakes the exception chain. It is perfectly fine to catch an exception, handle it and re-throw so that the calling code can see it, but you should be doing so like this:
catch (Exception ex) { /* handling code; */ throw; }

Why would you catch the expection to just throw it again, if you were to catch the exception and do something other than just throw it, it would be fine!
try
{
}
catch(Exception ex)
{
// do something like log the exception
throw ex; // let another catch block handle the expection.
}

Related

Exception thrown from within orElseGet is wrapped with UndeclaredThrowableException

In one of our service classes, we are throwing an exception to deal with in the controller. However, in one of the cases, the exception is from within orElseGet.
def function() throws CustomException {
try {
ProjectAssignment assignment = workspaceRepositoryService.getWorkspaceMembership(command.assigneeEmail, workspaceId).map {
createOrUndelete(it, project, command.assigneeRole, createdBy)
}.orElseGet {
...
try {
Invitation invitation = workspaceService.inviteUserToWorkspace(command.assigneeEmail, workspace, createdBy) // throws CustomException
} catch (Exception e) {
throw e // getting CustomException
}
...
}
} catch(Exception e) {
throw e // getting UndeclaredThrowableException wrapping CustomException
}
}
The exception thrown inside orElseGet is wrapped with UndeclaredThrowableException. Is there a way to preserve the type of thrown exception?
...
catch( UndeclaredThrowableException e){
throw e.getCause()
}
catch(Exception e){
throw e
}

Handling CompressorException in Java8 Streams

I have a static method for reading .bz2 files, it throws checked IOException and org.apache.commons.compress.compressors.CompressorException. The function signature is:
private static MyClass readFile(String fileName) throws IOException, CompressorException{
//…
}
Trying to use this method outright with Java8 streams gets compile time errors in Intellij;
unhandled exceptions: java.io.IOException, org.apache.commons.compress.compressors.CompressorException
So following advice from here, among others, I’ve tried the following but am stuck on how to handle the CompressorException object. Following it’s ctor I’ve tried as below but Intellij still complains the CompressorException is unhandled:
files.stream().forEach(i -> {
try{
readFile(i);
} catch (IOException e){
throw new RuntimeException(e);
} catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
});
Thanks
As #JB Nizet mentioned in the comment, you cannot throw any Exception from the lambda function inside foreach function.
You need to replace your current implementation:
catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
to either the following or not throw the RuntimeException at all.
catch (Throwable ex){
throw new RuntimeException("compressorException", ex);
}
The reason for the above behaviour is that the Stream.foreach() method has the following signature and doesn't throw any exception as part of the signature.
void forEachOrdered(Consumer<? super T> action)

How to Handle exceptions occured in jdbc code in servlet class [duplicate]

I am writing the servlet , in case of exception I am redirecting to my customized error page for that i have done like this.
In web.xml
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/WEB-INF/jsp/ErrorPage.jsp</location>
</error-page>
In Servlet,
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try{
//Here is all code stuff
Throw new Exception();
}catch(Exception e){
e1.printStackTrace();
}
But here ErrorPage.jsp is not displaying , where I am going wrong can anyone explain me?
You're catching the exception, and only printing the stacktrace inside, so the error-page doesn't take affect, remove the try-catch or re-throw and it will work. In addition, you have some syntax errors. Try something like
try{
//Here is all code stuff
throw new Exception();
}catch(Exception e){
e.printStackTrace();
throw new ServletException();
}
The problem is that you catch the Exception and therefore no Exception will leave your doPost() method. You will only be redirected error page if an Exception matching the <exception-type> (either identical or a subclass of it) leaves your doPost() method.
You should rethrow the Exception bundled in a RuntimeException for example:
} catch(Exception e) {
e1.printStackTrace();
throw new RuntimeException(e);
}
Unfortunately if we're talking about a general Exception you can't just not catch it because doPost() is declared to only throw instances of ServletException or IOException. You are allowed not to catch those, but java.lang.Exception must be caught.
You have handled the Exception in your doPost() using ,
try{
//Here is all code stuff
Throw new Exception();
}catch(Exception e){
e1.printStackTrace();
}
try and catch blocks. so the errorPage.jsp will not be invoked. <error-page> is invoked for unhandled exceptions
A nice example tutorial Exception Handling
Read for more info Best practice error handling in JSP Servlets

Cannot handle FaultException by reflection invoking

I am preparing a client for WCF service.
I provoked an fault exception in some method on a service site. I mean:
throw new FaultException<sth>(new sth())
When I catch this exception in WPF appliction:
catch (FaultException<sth> ex)
{
// something
}
everything works very clearly.
My point is, that I made a reflection on the service interface.
var type = typeof (someServiceInterface);
type.GetMethods();
and I want to catch the FaultException, when I call the method service in this way
try
{
var singleMethod = //do sth to get method
var result = singleMethod.Invoke(proxy, parameters);
return result;
}
catch (FaultException<sth> ex)
{
//1
}
catch (Exception ex)
{
//2
}
But I catch an Exception in second catch, not in the first. The type of this Exception is "System.Reflection.TargetInvocationException". I am confused and I wonder what cause such kind of problem.

does numberformatexception catch nullpointerexception?

does try catch of NumberFormatException could handle NullPointerException? and does try catch of Exception could handle any type of exception?
try {
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
Any sub-class of Exception you can see there is going to be catched by the try catch Exception.
NumberFormatException and NullpointerException are also Exception, but they're neither a sub-class of each other. That is, the first try-catch you stated won't catch a NullPointerException and vice-versa.
your syntax doesn't make sense, you can catch multiple exceptions, the most specific/narrow class of exception higher on the list:
try {
..code here...
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}