Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal exception handling in Java

Tags:

java

I am creating a basic math parser with Java and doing this is revealing my shallow understanding of Java exception handling.

when I have this input:

String mathExpression = "(3+5";

and I subsequently call:

throw new MissingRightParenException();

the IDE forces me to surround with a try/catch like so:

             try {
                    throw new MissingRightParenException();
                } catch (MissingRightParenException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                }

however, in order to force this to be a fatal exception, it looks like I have to add my own code to call System.exit(), like so:

             try {
                    throw new MissingRightParenException();
                } catch (MissingRightParenException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.exit(0);
                }

I am not sure I understand the syntax behind all of this, especially why I have to use a try/catch block around throwing an exception.

what is the rhyme and reason behind this?

Instead of throwing the exception, I could do this instead:

new MissingRightParenException();

instead of calling

throw new MissingRightParenException();

so I guess my question is - if this is a fatal exception, what is the best way to make it truly fatal while giving the user the best feedback?

like image 391
Alexander Mills Avatar asked Feb 01 '15 22:02

Alexander Mills


People also ask

How do you handle a fatal exception in Java?

You can just specify throws Exception for the main method to let the console receive the stack traces. So in the end: use throws in the signature of your methods instead of catching exceptions before you want to handle them.

What is fatal exception?

What Does Fatal Exception Mean? A fatal exception is an error condition that indicates access to either invalid data values or illegal instructions. The invalid privilege level to an operation can also cause fatal exceptions.

What is fatal in Java?

Fatal errors are errors such as native memory exhaustion, memory access errors, or explicit signals directed to the process.

Are runtime exceptions fatal?

Runtime exceptions indicate error conditions at runtime, and do not necessarily indicate fatal errors. Instead, they indicate that runtime conditions are invalid, such as the loss of database connection. All of these exceptions should be handled in a try-catch block.


1 Answers

If you want to have a checked exception that you have to catch - but not right away - then you can define throws MissingRightParenException in the signature of your methods.

class MissingRightParenException extends CalculationException {
    ...
}

class CalculationException extends Exception {
    ...
}

class MyClass {

    int myMathRelatedMethod(String calculation) throws CalculationException {
        ...
        if (somethingWrong) {
            throw new MissingRightParenException("Missing right paren for left paren at location: " + location);
        }
        ...
    }

    public static void main(String ... args) {        
        ...
        try {
            myMathRelatedMethod(args[0]);
        } catch (CalculationException e) {
            // stack trace not needed maybe
            System.err.println(e.getMessage());
        }
        ...
    }
}

You can also define it as the cause of a RuntimeException but that doesn't seem a good match for your current problem.

try {
     ...
     throw new MissingRightParenException();
     ...
} catch (MissingRightParenException e) {
     // IllegalStateException extends (IS_A) RuntimeException
     throw new IllegalStateException("This should never happen", e);
}

If your MissingRightParenException class extends RuntimeException then you don't have to catch it. The message will fall through all methods where it (or it's parent classes such as Throwable, Exception and RuntimeException) is not explicitly caught. You should however not use RuntimeExceptions for input related errors.

Usually the user will get the stack trace or at least the error message, although that depends of course or the error handling further down the line. Note that even main does not have to handle exceptions. You can just specify throws Exception for the main method to let the console receive the stack traces.

So in the end: use throws in the signature of your methods instead of catching exceptions before you want to handle them.

like image 190
Maarten Bodewes Avatar answered Sep 20 '22 13:09

Maarten Bodewes