简体   繁体   中英

Throwing custom exceptions in Java versus built in exceptions

I'm a little confused because I want to be able to throw a custom exception in Java. To do this inside a function, I have to add throws MyException to the header of the function.

And then anything that calls that function in turn must add throws MyException or have a try-catch block. But why is this?

For example, when creating a Stack in java and calling the pop function, I don't have to have a try-catch and yet the pop method in Java throws a NoSuchElementException (or w/e it is) if there isn't an element on the stack.

NoSuchElementException is a RuntimeException (un-checked exception) and we don't need to handle or declare RuntimeException S, thus the compiler wont complain, but instead throw it at runtime.

In the case of checked exceptions ie, all the exceptions which are not subtypes of RuntimeException , the compiler will check for a suitable catch clause, enabling the program to continue its course of execution, after performing the operations within the catch ; to do this, you need to handle them using try/catch blocks or declare them using the throws clause - delegating the responsibility of handling the exception higher up the call chain. If your custom exception is not a RuntimeException rules of checked exceptions apply to your custom exception as well.

Checked exceptions ---> Forced by the compiler to handle or propagate

Un-checked exceptions ---> Not checked by the compiler thus appears at runtime

Java has so called checked exceptions and unchecked exceptions. A checked exception must be declared in method signature, an unchecked exception does not need to be declared.

If you want to define an unchecked exception yourself derive it from RuntimeException insted of Exception .

你应该抛出或尝试捕获所有已检查的异常,它不是RunTimeException必需的,而你所讨论的异常是一个RuntimeException

See my answer to this question.

As a general rule of thumb, when deciding whether or not to create a custom exception class, I try and use the built-in exception classes as much as possible, where it makes sense to do so, eg IllegalArgumentException , etc.

Here is an example of how to create a custom RuntimeException , which, as you have discovered, will not require a try/catch/finally block, or a throws clause.

public class MyRuntimeException extends RuntimeException {
    public MyRuntimeException() {
        super();
    }

    public MyRuntimeException(String message) {
        super(message);
    }
}

public class MyClass {
    public void go(int val) {
        if(val <= 0) throw new MyRuntimeException("Val must be greater than 0.");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM