How to throw an Exception when your method signature doesn't allow to throw Exception?

后端 未结 3 1646
感动是毒
感动是毒 2021-01-31 18:58

I have a method like this:

public void getSomething(){
...
}

I want to throw an Exception inside getSomething(). The

3条回答
  •  不要未来只要你来
    2021-01-31 19:28

    Java has two kinds of exceptions, checked and unchecked. You must declare checked exceptions, but you don't have to declare unchecked exceptions.

    RuntimeException is the basic unchecked exception, so you can throw that without declaring it.

    public void getSomething(){
       throw new RuntimeException("I don't have to be declared in the method header!");
    }
    

    As a side note, you probably don't want to throw a raw RuntimeException, but subclass it to something more specific to your needs. Any subclass of RuntimeException will be unchecked as well.

提交回复
热议问题