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:
How can I find out, for any exception, either checked or unchecked, what the default message would be that the JVM would display?
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?
- 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.
- 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);
}
}
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
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