Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, default exception messages

Given the following:

public abstract class Test {
    public static void main(String[] args) {
        int[] testArray = {6, 3, 2};
        System.out.println(testArray[3]);
    }
}

when I run the program I get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Test1.main(Test1.java:5)

In this case the JVM displays the index that is out of bounds i.e. 3.

This specific example aside, given that I choose not to catch an exception in a program's code:

  1. How can I find out, for any exception, either checked or unchecked, what the default message would be that the JVM would display?

  2. For a custom exception class that I write myself, and for an object of this class that I generate in my code using the 'throw' keyword (but, again, choose not to catch), can I set up a default message that the JVM would display?

like image 595
danger mouse Avatar asked Dec 14 '22 14:12

danger mouse


2 Answers

  1. How can I found out, for any exception, either checked or unchecked, what the default message would be that the JVM would display?

As you might already suspect, the answer is "in general, you can't". Most of the time, the message is set from one of the constructors of the exception that takes a string message. If you're lucky, the message will be meaningful and provide useful information. Otherwise, as is common practice, the semantics of the exception will reside essentially in its class name and in the associated Javadoc. Also consider that exception messages are often localized.

  1. For a custom exception class that I write myself, and for an object of this class that I generate in my code using the 'throw' keyword (but, again, choose not to catch it), can I set up a default message that the JVM would display?

That's entirely up to you. You could setup a default message in the default constructor like this:

public class MyException extends Exception {
  public MyException() {
    super("my default message");
  }

  public MyException(String message) {
    super(message);
  }
}
like image 59
Lolo Avatar answered Dec 30 '22 23:12

Lolo


There is Thread.setDefaultExceptionHandler, all the uncaught exceptions will go there, so you can provide your own exception handler as an argument to that method somewhere in the beginning of your program.

I think, you can also construct any exception yourself and see the message as follows

new IOException().getMessage()

though probably the message in that case will be empty, I didn't try

like image 32
Alexander Kulyakhtin Avatar answered Dec 30 '22 22:12

Alexander Kulyakhtin