質問

In Java, is the keyword (throw) only used for throwing exception that you've created. If not, can someone give an example of how it is used outside of your own made exceptions.

役に立ちましたか?

解決

You can throw anything that extends Throwable

void greet(String name) {
    if (name == null) {
        throw new IllegalArgumentException("Cannot greet null");
    }
    System.out.println("Hello, " + name);
}

他のヒント

No, the throw keyword can be used with any Exception, including built-in ones:

throw new IllegalArgumentException("Your value passed in was illegal");

As mention in JLS 14.18

The Expression in a throw statement must denote either 1) a variable or value of a reference type which is assignable (§5.2) to the type Throwable, or 2) the null reference, or a compile-time error occurs.

For example Consider the situation given below:

public void factorial(int num)
{
    if (num < 0 )
    {
        throw new IllegalArgumentException("Invalid number :"+num);
    }
    else
        //....code for factorial.
}

Here IllegalArgumentException is not the user defined exception. It is a built in RunTimeException and as specified in oracle docs:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

You can throw anything that extends Throwable including errors, your exceptions, and the java builtin exceptions.

It can also be used for more complex logic:

You can use it to rethrow, for example, ThreadDeathErrors among other exceptions. When a thread must die, it can catch this error:

catch(ThreadDeathError e){
    System.out.println("Thread going down");
    throw e;
}

Here, e is not your own exception, but an error that was caught. Please respect the differences between errors and exceptions as the former are not generally caught.

The thread death error must be rethrown to actually cause the theread to die.

throw can be used to thow any exception that extends java.lang.Throwable

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top