How to effectively handle any kind of exceptions? - java

Exception handling is the most useful mechanism to save the application from the crash. Even most of us following the exception handling mechanism. Even I see many of still getting the exceptions. Are we handling the exceptions in a way that supposed to? My question is, What is best way to handle any kind of exception?
I want to make few things clear. When I say handling an exception that does not only mean that capturing appropriate exception message and showing or logging it. Rather, it suppose to handle corrective action for exception.
Lets consider this piece of code:
try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (YourException e) {
System.out.println(e.getMessage());
}
In the above code, "MyException" and "YourException" may not catch all kind of Exception. But, of course we can use "java.lang.Exception". How would we identify the correct exception type? and how to handle that exception? especially when using external libraries.
More detail upon request.
Thanks

You do not want to capture Runtime exceptions. The reason being, you are just hiding a bug right there. Instead let the application fail and fix it. To answer to your questions, if you catch Throwable, you are going to basically eat up any kind of exceptions.
Rule of thumb: Only catch application exception.

I don't know if I'm actually getting the meaning of your question, but, you can catch as many expceptions as you need at a certain block of code:
try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (YourException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
//handle
} catch (SQLException e) {
//handle
}
And, based on exception hierarchy, when you catch a exception, you are also catching every subtype of this exception, so, when you need to catch every unexpected error condition, you can add a catch for java.lang.Exception (at the last catch statement)
try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (YourException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
//handle generic unexpected exception
}
You could also catch the super interface Throwable, but it's not recommended, as the only difference is that, aside the exceptions, you will catch the Errors too. The errors are fatal conditions, which should not be handled, as they use to mean serious problems at the java VM, as Out of Memory, Stack Overflow, etc.
These links can be useful on how to handle java Exceptions:
http://download.oracle.com/javase/tutorial/essential/exceptions/index.html
http://tutorials.jenkov.com/java-exception-handling/index.html
Regards.

Guys from Software Engineering Radio podcast had two very good episodes on Error Handling.

If you really want to catch every possible exception, catching Throwable is what you want to do:
try {
somethingThatMayFail();
} catch (Throwable t) {
t.printStackTrace();
}
More often than not, this is a bad idea, though. You shouldn't catch any exceptions if you don't know why they occurred, or how to clean up after them. Not crashing is not necessarily a good thing - if your program is broken, crashing is the responsible thing to do. Consider this method:
public Thing loadThing(long id){
try {
return doLoad(id);
} catch (Throwable t) {
// What do we do here?
}
}
The compiler forces you to return or throw something from every possible execution path of the method, but only the non-exceptional path allows us to return something sensible. We could return null from the catch clause, but then the calling code might forget checking the return value for null, which means you'll instead end up with a NullPointerException which is far harder to decipher since it doesn't tell you what the real error was or where it occurred.
Exceptions are good. There are reasons why every sensible language has them.

The type of any object can be inspected via reflection. But i don't like using it much.
try {
throw new Exception1();
} catch (Throwable t) {
// just get name
System.out.println(t.getClass().getName() + " caught");
// or try instanceof - this is not nice approach IMO
if (t instanceof Exception1) {
System.out.println("yes exception1");
}
}
BTW did think or heard about AOP? To be more precise about AspectJ. Aspect oriented programming can be answer to your question how to print or log exceptions while your code is still clean and easily maintainable. If you are using Java EE and EJB, you can try interceptors mechanism instead of AspectJ. I recommend you read something about AOP and AspectJ (for Java).
cheers

It sounds like you're trying to figure out how to know when you've handled every possible exception. If you just don't put a throws clause on your method then the compiler will tell you which exceptions you need to put handlers for.

If you are using Eclipse, one way is to write the code with out exception handling and it will make you see the types of exceptions that your code might throw.
If you want your program sequence to continue as you have coded, then you can surround only that part of code that might throw an exception and in the Catch block perform necessary steps so that your program works in the flow you want.
something like
"
code ...
try{
something....
}catch(someException e){
// handle it
}
try{
something....
}catch(someException e){
// handle it
}
code ...
"
However this code does not catch any exception that may occur otherwise (i.e, not because of your code). For that an Outer Try Catch might help you find out that it was something else
like
"
try
{
code ...
try{
something....
}catch(someException e){
// handle it
}
try{
something....
}catch(someException e){
// handle it
}
code ...
}
catch(runtime e){
//tell user/log that something unexpected has occured
}
"

Your code is correct. If someMethod1() method does not declare any other Exceptions, they are RuntimeExceptions and you are supposed to catch RuntimeException.

Related

Java: Caught exception is immediately rethrown? What's the problem?

I have the following Java code (that I thought was OK) but the IDE is warning me that "IOExcpetion e is immediately rethrown."
I'm new to exception handling in Java, and I wasn't aware there was anything wrong with doing that.
From what I'm reading, it looks like my other options is to simply delete the catch block and replace it with a finally block... but then it warns that the finally block is empty.
I don't have any ideas on what I should do differently.
private InputStream getFlutterAssetAsInputStream(String fromAsset) throws IOException {
String assetPath = binding
.getFlutterAssets()
.getAssetFilePathBySubpath(fromAsset, PACKAGE_NAME);
try {
return binding.getApplicationContext().getAssets().open(assetPath);
} catch (IOException e) {
throw e;
}
}
This
try {
return binding.getApplicationContext().getAssets().open(assetPath);
}
catch (IOException e) {
throw e;
}
is functionally equivalent to this:
return binding.getApplicationContext().getAssets().open(assetPath);
Your IDE is telling you that your try-catch is pointless. It does nothing.
So what do you want to do?
Pass the exception on to your caller? In which case get rid of the try-catch
Signal a different exception on to the caller - maybe one with a more appropriate error message for the specific circumstances? Then make and throw a new exception object with a better error message.
Do something to handle the situation - at the very least, maybe display an error message? Log the event to enable debugging? Then write code in the catch-block to do that. And then you have to decide what happens next.
Fundamentally, this is a design issue. IO errors happen. So how does this method that you're writing want to handle IO errors?

About Methods And Try, Catch Handler in Java

So, Here In Java I Am Not Understanding What is Exception e? What does e stand for, in a catch statement?
Thank You For correcting my statement!
It is the recommended sintax in catch block, the Exception is the class of the exception and the "e" is the variable that will hold the excepcion object instance.
In some cases you will see that a method has more than one catch block so that different exceptions can be managed, in those cases the "e" will vary:
catch (FileNotFoundException fnfe) {
// code to manage file not found exception
}
catch (IOException ioe) {
// code to manage the I/O exception
}
catch (Exception e) {
// code to manage generic exception
}
Remember that the order of the catch blocks matters, it goes from top to bottom so if there is a FileNotFoundException the rest will not be catched, as it is more specific.
More on this, it is considered a good practice to be as specific as possible when catching exceptions, you can see some more tips in this article:
https://dzone.com/articles/9-best-practices-to-handle-exceptions-in-java
The Exception Catching thing is a long debate in Java world :-)

Java know in finally that exception thrown without any variable [duplicate]

In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.
Is there a more elegant way of doing this? Perhaps an API call that will reveal this?
Here's some rough code of what I'm talking about:
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.
Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?
This question actually spawned from comments in another question that raised an interesting question.
Your idea about setting a variable outside the scope of the try/catch/finally is correct.
There cannot be more than one exception propagating at once.
Instead of using a Boolean flag, I would store a reference to the Exception object.
That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).
I think this is a missing C# language feature that should be added. The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be an easy task for the compiler, saving us the work of manually creating a local Exception variable and remembering to manually set its value before re-throwing an error, as well as preventing us from making the mistake of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).
finally (Exception main_exception)
{
try
{
//cleanup that may throw an error (absolutely unpredictably)
}
catch (Exception err)
{
//Instead of throwing another error,
//just add data to main exception mentioning that an error occurred in the finally block!
main_exception.Data.Add( "finally_error", err );
//main exception propagates from finally block normally, with additional data
}
}
As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of overwriting the main exception by throwing a new error (bad) or just ignoring the error (also bad), it could add the error as additional data to the original error.
You could always set a boolean flag in your catch(es). I don't know of any "slick" way to do it, but then I'm more of a .Net guy.
Use logging...
try {
stream.write(buffer);
} catch(IOException ex) {
if (LOG.isErrorEnabled()) { // You can use log level whatever you want
LOG.error("Something wrong: " + ex.getMessage(), ex);
}
throw ex;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not close in finally block", ex);
}
}
}
}
In vb.net, it's possible to use a "Catch...When" statement to grab an exception to a local variable without having to actually catch it. This has a number of advantages. Among them:
If nothing is going to 'ultimately' catch the exception, an unhandled exception trap will be fired from the spot of the original exception. Much nicer than having the debugger trap at the last rethrow, especially since information that might be needed for debugging won't yet have gone out of scope or been swept up by 'finally' statements.
Although a rethrow won't clear the stack trace the way "Throw Ex" would, it will still often jinx the stack trace. If the exception isn't caught, the stack trace will be clean.
Because this feature is unsupported in vb, it may be helpful to write a vb wrapper to implement the code in C (e.g. given a MethodInvoker and an Action(Of Exception), perform the MethodInvoker within a "Try" and the Action in a "Finally".
One interesting quirk: it's possible for the Catch-When to see an exception which will end up getting overwritten by a Finally-clause exception. In some cases, this may be a good thing; in other cases it may be confusing. In any event, it's something to be aware of.

Catch separate exceptions or use instanceof - Java 6

Assume that this piece of code is in 20 places and always the same
try {
// do something
} catch (FirstException e) {
// log it
} catch (SecondException e) {
// log it
}
Wouldn't be better to use something like this or instanceof is not good solution?
try {
// do something
} catch(Exception e) {
logException(e);
}
void logException(Exception e) {
if (e instanceof FirstException) {
// log it
} else if (e instanceof SecondException) {
// log it differently
} else {
// do something with other exception
}
}
The only thing that I really hate about the solution is catching Exception which is definitelly not the best way... Is there any better way?
In Java 7, use catch (FirstException1 | SecondException | ...)
There may be nothing wrong with catch (Exception e)—you do want to log all exceptions, don't you? I would in fact advise catch (Throwable t) because OutOfMemoryError s and StackOverflowErrors also want to be logged.
An advice from many years of experience with logging exceptions is to log them all the same way. The exception message is enough as human-readable text, and what the developer really needs for debugging is the stack trace.
Just be careful about one thing: never catch exceptions too early: catch them at a single place for the whole application, the so-called exception barrier—it is at the level where you enter and exit a unit of work.
If checked exceptions are giving you trouble at the lower level, wrap them into RuntimeException:
try {
...
}
catch (RuntimeException e) {throw e;}
catch (Exception e) {throw new RuntimeException(e);}
Only if you know precisely and in advance that there is an exception which has business-level meaning to your application, and will not abort the current unit of work, but redirect its flow, is it appropriate to catch that exception at a lower level. In practice such exceptions are rare compared to the totality of all possible exceptions thrown by the application code.
The first approach is definitely better. Generally it is a bad practice to catch Exception because in this case you catch RuntimeExceptions too.
Former is clean and great solution if you only have to log the exceptions.
Else first approach is better.
In the book "Refactoring to Patterns" one of the common refactorings is "replace instanceof with polymorphism" - in other words whenever you use instanceof, consider if polymporphism would in fact work better. . .
Having said that, for this particular question the Spring philosophy of replacing checked exceptions with runtime exceptions springs to mind (excuse the pun).
The idea is that checked exceptions can be overused - is the exception something that could be recovered from? If yes, ok. . . if not, just let it propagate up the chain. You can do this by:
Re-throwing it. . . (but better still)
Wrap it in a RuntimeException
Create a logging Aspect:
Another thing to consider is that if you do need to log these exceptions at precisely the point they occur rather than having them propagate up the chain, and that they occur in 20 different places, then they're a cross-cutting concern. . . You could have the regular method just rethrow the exception, and then write an aspect to catch and log them. . . . again using Spring makes this easy.

Handling exceptions in exception block

Could someone please provide some good practice to handle exceptions in exception for example I have
try {
...
DeserializationResult deserialization = xmlSerializationService.deserializeFromXml(node);
some code here
} catch (Exception e) {
try {
//I need to create process result xml with error code and some details
// creation of result xml document
} catch (Exception e) {
// maybe some error message here
}
}
can I somehow make this code looks clearer, noiseless and easier to understand?
Thanks for answers. P.S. I know that using general exception is not good practice, its just for example purpose here.
The first approximation for solving that problem is usually to put the logic of the catch in a separate method, and only have one line in the catch block (the method call).
Always catch specific exceptions, not the general Exception superclass.
If I look at that code, I'm not sure what can go wrong. If you specifically catch exceptions, it's much easier to see what failures you are expecting and catering for.
Also handle each failure in a specific way that makes sense for that failure. The simplest form of that is to return a result that describes the failure.
Maybe something like:
try{
//DeserializationResult deserialization = xmlSerializationService.deserializeFromXml(node);
//some code here
}catch(NullPointerException npe){
//Maybe return something like: new DeserializationResult("xmlSerializationService not initialized")
}catch(DeserializationException dse){
//Maybe return something like: new DeserializationResult("Could not deserialize because ...")
}

Categories