Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to do when catching e(rror) in Java

Tags:

java

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?

Example 1 : printStackTrace()

} catch (SomeException e) {
    e.printStackTrace();
}

Example 2 : getMessage

} catch (SomeException e) {
    e.getMessage();
}

Example 3 : show custom error message

} catch (IOException E) {
    System.out.println("Error occured. Please try again.");
}
like image 707
kenju Avatar asked Aug 07 '15 10:08

kenju


People also ask

How do you handle errors in catch block?

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.

What is error catching in Java?

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.

Should you catch an error in Java?

As I said before in Java Exception best practices post, Ideally you should never catch Throwable or in particular Error.

How do you handle catch block in Java?

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.


2 Answers

In short, the answer is depends. Do what your business logic asking for.

  • If you want to log it, log it.
  • If you want to see the error in console, print it to there.
  • If you want to throw back to the method caller, go do it.

There are no of possibilities and needs depending on the situation.

like image 122
Suresh Atta Avatar answered Nov 03 '22 04:11

Suresh Atta


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);
like image 38
Amila Avatar answered Nov 03 '22 04:11

Amila