Handling exceptions in exception block - java

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 ...")
}

Related

Is there a point to handle exceptions in selenium besides for logging purposes?

I am finding it hard to understand the point of exception handling in selenium.
For example, if I try to click on an element, and the element could not be found then NoSuchElementException occurs.
I can catch the exception, throw new RunTimeException, or do nothing. The result will be the same ( the program will fail and stop ).
Why would I bother to handle such an exception?
Am I missing something here?
thanks
public void clickOnElement(MobileElement element, Integer waitInSeconds){
waitInSeconds = (waitInSeconds != null ? waitInSeconds : this.secondsToWait);
try {
waitFor(ExpectedConditions.elementToBeClickable(element),waitInSeconds);
element.click();
} catch (Exception e) {
System.out.println("Could not click on element");
e.printStackTrace();
}
}
Exception handling for Selenium is a great way to proof your tests against unexpected conditions. For example, you can try to find the element again if it is no longer attached to the page, for example after a javascript is executed that changes something in the element.
try{
driver.findElement(By.id("MyId")).click();
} catch (StaleElementReferenceException e){
driver.findElement(By.id("MyId")).click();
}
Or, for example, you can ignore if an element does not appear, for example, a GDPR overlay at the top of the page after logging in.
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("gdpr_overlay")));
} catch (TimeoutException ignored){
}
This will ignore the exception thrown by the wait if the overlay does not appear and continue to run your test.
Exceptions are very useful features, far more useful than just for logging, you should look it up.
You can do whatever you want in the catch block, you can try to click a different element if the first one failed, redirect to another page... The possibilities are endless really.
Advice: Avoid generic exceptions, you should catch specific exceptions and react accordingly, and in the last catch block you can do generic Exception e and throw an error.
Firstly ExceptionHandling is not a concept of Selenium but it is related to JAVA. Now coming to the usage of handling exceptions it has a lot of depth to the concept which you will understand while constructing frameworks but as of now it is important to understand by handling exceptions you can continue to execute your code without JVM terminating the rest when it comes across an exception.
try{
}
catch{
}
finally
{
}
Finally is also very helpful when you always want to execute a block of code irrespective of whether ur scenario is going to pass or fail for example like driver.close().
Hope that helped ... Happy coding :)

Java Best practice when an exception in caught into java code function

I'd like to know what is the best way or best-practice to handle this kind of situation. Guess a straightforward function like this:
public Object f1() {
Object result = null;
try {
String payload = methodThrowsAnException();
result = payload;
} catch (IOException e) {
throw new IllegalStateException(e); <<<<<<<<<<<<<<<
}
return result;
}
I'd like to know if it's a good practice:
to re-throw the exception or
return a null when something has been wrong inside.
I don't know if I've explained so well.
Re-throwing caught exception is a bad idea. most often, the stacktrace will contain more or less detailed information about your architecture. This would be to useful for an attacker.
I wouldn't allow my app to get into illegal state because of the user's action. In your case, I would say:
try {
String payload = methodThrowsAnException();
result = payload;
} catch (IOException e) {
throw new IllegalArgumentException(<user's input which caused the exception>); <<<<<<<<<<<<<<<
}
There is nothing wrong with returning a null from your method if there is a particular scenario where you expect that exception.
Alternatively you can just allow the Exception to bubble up, and be handled by the caller.
When would I catch and re-throw an exception? When I can convey better meaning by throwing a new exception.
Would I include the original exception when I throw a new one? I would do it if it is a unknown/unexpected scenario which requires further debugging.
Let me share some examples:
Something unrecoverable like Out of DB Connection. I would just let the exception bubble up. It should get handled just before it reaches the user, and probably end up in a generic error message like 'Service not available. Please try again later'.
Something application related... such as backup file not found. In that case I will swallow up the FileNotFoundException and instead I will throw a BackupFileMissingException which is specific to my application. Here I don't need to include the FileNotFoundException because it is an expected scenario and there is nothing further to investigate.
I call some other API and they throw an exception, which is not documented. In this case, I will translate it into my application exception such as InterfaceApiException and include the original exception, so that it can be logged at the REST/Action layer along with the root cause.

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.

How to effectively handle any kind of exceptions?

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.

Java - How to do Python's Try Except Else

How do I do a try except else in Java like I would in Python?
Example:
try:
something()
except SomethingException,err:
print 'error'
else:
print 'succeeded'
I see try and catch mentioned but nothing else.
I'm not entirely convinced that I like it, but this would be equivalent of Python's else. It eliminates the problem's identified with putting the success code at the end of the try block.
bool success = true;
try {
something();
} catch (Exception e) {
success = false;
// other exception handling
}
if (success) {
// equivalent of Python else goes here
}
What about this?
try {
something();
} catch (Exception e) {
// exception handling
return;
}
// equivalent of Python else goes here
Sure, there are some cases where you want to put more code after the try/catch/else and this solution don't fit there, but it works if it's the only try/catch block in your method.
While Ryan's answer of tracking errors with boolean(s) is nice, I think using a "logic block" to "skip forward" is better in this case.
In Java, you are allowed to create arbitrary context blocks (scopes) using <optional-label-name followed by ':'>{...} and assign labels to them. You can than call break <labelname>;
Here is an example of what I mean that you can play with:
private static void trycatchelsetest(boolean err) {
myLogicBlock: {
try {
System.out.println("TRY");
{ //unlabeled block for demonstration
if(err)
throw new IOException("HELLO!");
}
} catch(IOException e) {
System.out.println("CATCH");
break myLogicBlock;
} finally {
System.out.println("FINALLY");
}
System.out.println("ELSE");
}
System.out.println("END");
}
The reason Try doesn't have an else is because it is meant to catch a specific error from a specific block of code, which is either handled (usually by setting a default or returning), or bubbled up (and finally is offered only to make sure resources aren't leaked because of the interrupt, even if you break out). In the break example above, we are handling the exception by skipping the block of code that is no longer relevant because of the error (skipping forward to the next logical step). The boolean example by Ryan handles it by noting the error happened, and letting latter parts of the code react to it happening after the fact.
I think the logic block is better than the boolean approach (as long as you have no complex logic based on what errors have been thrown) because it doesn't require the reader to know the entire function to understand what happens. They see break <labelname>; and know that the program will effectively skip forward to the end of that block. The boolean requires the programmer to track down everything that makes decisions on it.
Obviously, "Skip-forward" and Boolean tracking each have their own advantages, and will usually be more a style choice.
While there is no built-in way to do that exact thing. You can do something similar to achieve similar results. The comments explain why this isn't the exact same thing.
If the execution of the somethingThatCouldError() passes, YAY!! will be printed. If there is an error, SAD will be printed.
try {
somethingThatCouldError();
System.out.println("YAY!!");
// More general, code that needs to be executed in the case of success
} catch (Exception e) {
System.out.println("SAD");
// code for the failure case
}
This way is a little less explicit than Python. But it achieves the same effect.

Categories