Throw keyword in Java [closed]

泪湿孤枕 提交于 2019-12-25 19:07:42

问题


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.


回答1:


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);
}



回答2:


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

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



回答3:


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.




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/17579226/throw-keyword-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!