Throwing exceptions in Java

后端 未结 11 956
萌比男神i
萌比男神i 2020-12-30 16:23

I have a question about throwing exceptions in Java, a kind of misunderstanding from my side, as it seems, which I would like to clarify for myself.

I have been read

11条回答
  •  长发绾君心
    2020-12-30 16:43

    With the first way do you mean something like this:

    try {
      ok = doSomething();
      if (!ok) {
       throw new Exception("Error");
      }
     ok = doSomethingElse();
    }catch (Exception e) {
    }
    

    This will allow you to exit the try-catch block without executing the rest of it. This is the only valid usage I can think of throwing an exception with throw and catching it yourself in a try-catch block. However, standard if blocks should be used instead. I don't understand why someone should throw an exception and then catch it himself.

    The second way is more standard, especially if the caller of the method that throws an exception is an external module. This is a way of signaling that something real wrong happened. It is the responsibility of the caller to handle the exception.

提交回复
热议问题