I am new to Java and exceptions in general.
In my prior C/Perl programming days, when I wrote a library function, errors were passed back by a boolean flag, plus some kind of string with a human-friendly (or programmer-friendly) error message. Java and C++ have exceptions, which is handy because they include stack traces.
I often find when I catch an exception, I want to add my two cents, then pass it along.
How can this be done? I don't want to throw away the whole stack trace... I don't know how deep the failure occurred and for what reason.
I have a little utility library to convert a stack track (from an Exception object) into a string. I guess I could append this to my new exception message, but it seems like a hack.
Below is an example method. Advices?
public void foo(String[] input_array) {
for (int i = 0; i < input_array.length; ++i) {
String input = input_array[i];
try {
bar(input);
}
catch (Exception e) {
throw new Exception("Failed to process input ["
+ ((null == input) ? "null" : input)
+ "] at index " + i + ": " + Arrays.toString(input_array)
+ "\n" + e);
}
}
}
In order to create custom exception, we need to extend Exception class that belongs to java.lang package. Consider the following example, where we create a custom exception named WrongFileNameException: public class WrongFileNameException extends Exception { public WrongFileNameException(String errorMessage) {
The "throw" keyword is used to throw an exception. The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
Exceptions can be chained:
try {
...
} catch (Exception ex) {
throw new Exception("Something bad happened", ex);
}
It makes original exception the cause of the new one. Cause of exception can be obtained using getCause()
, and calling printStackTrace()
on the new exception will print:
Something bad happened ... its stacktrace ... Caused by: ... original exception, its stacktrace and causes ...
Typically you throw a new exception which includes the old exception as a "cause". Most exception classes have a constructor which accept a "cause" exception. (You can get at this via Throwable.getCause()
.)
Note that you should almost never be catching just Exception
- generally you should be catching a more specific type of exception.
Just use a different constructor:
Exception(String message, Throwable cause)
The message is your "two cent" and you include the catched exception, which will be shown in a stacktrace printout
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