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?
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()
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.
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.
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.
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.
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