Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Exception vs Exception.getMessage

Tags:

java

exception

Is there a best practice on using the followng two pieces of code regarding exceptions.

//code1  } catch (SomeException e) {     logger.error("Noinstance available!", e.getMessage()); }  //code2 } catch (SomeException e) {     logger.error("Noinstance available!", e); } 

When should I use the getMessage method of an exception?

like image 893
DesirePRG Avatar asked Sep 29 '15 09:09

DesirePRG


People also ask

What is exception getMessage ()?

The getMessage() method of Throwable class is used to return a detailed message of the Throwable object which can also be null. One can use this method to get the detail message of exception as a string value. Syntax: public String getMessage()

What are the different ways to print exception message on console?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

What is the use of getMessage?

The GetMessage function retrieves messages associated with the window identified by the hWnd parameter or any of its children, as specified by the IsChild function, and within the range of message values given by the wMsgFilterMin and wMsgFilterMax parameters.

How many ways we can print exceptions in Java?

In Java, there are three methods to print exception information. All of them are present in the Throwable class. Since Throwable is the base class for all exceptions and errors, we can use these three methods on any exception object.


1 Answers

The first doesn't compile because the method error accept a String as first parameter and a Throwable as second parameter.

e.getMessage() is not a Throwable.

The code should be

} catch (SomeException e) {     // No stack trace     logger.error("Noinstance available! " + e.getMessage()); } 

Compared with

} catch (SomeException e) {     // Prints message and stack trace     logger.error("Noinstance available!", e); } 

The first prints only a message. The second prints also the whole stack trace.

It depends from the context if it is necessary to print the stack trace or not.

If you already know why an exception can be thrown it is not a good idea to print the whole stack trace.

If you don't know, it is better to print the whole strack trace to find easily the error.

like image 200
Davide Lorenzo MARINO Avatar answered Sep 26 '22 10:09

Davide Lorenzo MARINO