In Java, I see a lot of codes like below. What I am wondering is, is it enough just to show error message?
I am new to Java. What I want to learn is how to handle error efficiently, and know best practices for error-handling. In general, what should I do in catch block?
} catch (SomeException e) {
e.printStackTrace();
}
} catch (SomeException e) {
e.getMessage();
}
} catch (IOException E) {
System.out.println("Error occured. Please try again.");
}
You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.
The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
As I said before in Java Exception best practices post, Ideally you should never catch Throwable or in particular Error.
Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.
In short, the answer is depends. Do what your business logic asking for.
There are no of possibilities and needs depending on the situation.
I'd recommend you starting with Exception section in Java tutorial.
What you should do in the catch block depends on your application.
Generally, if you're just logging the error, you should include the stacktrace to make debugging easier.
logger.error("Error occurred.", e);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With