Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an exception message in a String variable in java?

Tags:

java

I need to process an exception message when any exception is caught in Java.

I am working on a Database Connection class. When I give wrong details like username, password, host name, sid, etc, the control goes to catch block and gives an error. I would like to get this error message on the JSP side and redirect to the same page with that error message. However, when I get the error message in Java, it always takes a null value.

My code example is here.

String errorMessage = null;
try{
// CODE Where Exception occure
}catch(SQLException se){
    errorMessage = se.getMessage();
}catch(Exception e){
    System. out.println("In Exception block.");
    errorMessage = e.getMessage();
}finally{
    System.out.println(errorMessage);
}

It will go to Exception block but the errorMessage is null.

like image 447
Anand Maheshwari Avatar asked Aug 24 '14 16:08

Anand Maheshwari


People also ask

How do I extract an exception from a message in Java?

Following are the different ways to handle exception messages in Java. 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.

How do you pass an exception as a parameter in Java?

To throw an exception, we generally use the throw keyword followed by a newly constructed exception object (exceptions are themselves objects in Java). Most exception constructors will take a String parameter indicating a diagnostic message.

How do I write an exception message?

In my experience, when it comes to writing exception messages, most developers approach the job with one of these mindsets: Write the shortest possible exception message; if possible, ignore good grammar, punctuation, and proper spelling. Write lovingly crafted error messages for the end users.

Which method helps print exception message?

The Throwable class provides the following three methods to print the exception message: Using printStackTrace Method. Using getMessage() Method. Using toString() Method.


2 Answers

At first, the answer of @Artem Moskalev should be right in most ways. In your case, you'd said:

It will goes to Exception block but the errorMessage is null.

So, let's try two cases to debug the behavior:

First:

class Test1
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String errorMessage = null;
            try{
                throw(new Exception("Let's throw some exception message here"));
            }catch(Exception e){
                System.out.println("In Exception block.");
                errorMessage = e.getMessage();
            }finally{
                System.out.println(errorMessage);
            }
    }
}

Output:

In Exception block.
Let's throw some exception message here

Seems to work like you expected.


Second:

class Test2
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // String errorMessage = null;
        // To make the difference between non-initialized value 
        // and assigned null value clearer in this case,
        // we will set the errorMessage to some standard string on initialization
        String errorMessage = "Some standard error message";
            try{
                throw(new Exception());
            }catch(Exception e){
                System.out.println("In Exception block.");
                errorMessage = e.getMessage();
            }finally{
                System.out.println(errorMessage);
            }
    }
}

Output:

In Exception block.
null

Why is that? Because you're accessing e.getMessage(), but if the message is emtpy e.getMessage() will return null. So the null isn't from the initialization, but from the return value of e.getMessage(), when e doesn't have any error message (for example if there is a NullPointerException thrown).

like image 65
ConcurrentHashMap Avatar answered Sep 20 '22 06:09

ConcurrentHashMap


This block is always executed:

...finally{
    System.out.println(errorMessage);
}

If your errorMessage has not been assigned any other value before (ie. no exception thrown in your try clause) - System.out.println will print you the errorMessage value which is null.

like image 35
Artem Moskalev Avatar answered Sep 19 '22 06:09

Artem Moskalev