문제

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