Why do you have to write throws exception in a class definition?

前端 未结 9 1154
逝去的感伤
逝去的感伤 2020-12-31 09:04

Coming from C#, I just don\'t get this \'throws exception\' that is written after a class/method definition:

public void Test() throws Exception


        
相关标签:
9条回答
  • 2020-12-31 10:01

    You don't have to write it in all cases -- you just have to write it if your method throws a checked Exception (an exception that is a subclass of Exception and not a subclass of RuntimeException). This is because your method signature is a contract, and it's declaring to all the code which calls it that it has the potential for throwing the given exception. Because it's a checked exception -- an exception which can be anticipated -- the calling code needs to anticipate the potential of seeing the exception thrown, and needs to be able to handle it.

    To answer your two specific questions:

    • do you have to write it/what if you don't: if your method throws a checked exception, then yes, you have to declare it in your method signature. If you don't, then your code won't compile.
    • do you have to catch it: you have to do something with it. The code calling the method can either catch it and handle it, it can catch it and re-throw it, or it can just pass it up the chain. In order to pass it up the chain, the code calling the method has to itself declare that it throws the same exception -- e.g., if method bar can throw SomeException, and method foo calls bar and doesn't want to catch the exception, the method signature for foo would declare that it too throws SomeException.

    The Exceptions chapter of the Java lessons is very good at explaining this in detail, and JavaWorld has a good article about throwing and catching exceptions that I've always found to be a good reference to pass onto folks.

    0 讨论(0)
  • 2020-12-31 10:05

    "throws" keyword is used if the exception may not gonna handle in current method and it can be propagated to the caller of that method.

    The caller can either handle that exception or propagate that exception to another method by using "throws" keyword.

    The Exception class is base class for Runtime Exception.

    0 讨论(0)
  • 2020-12-31 10:08

    You don't have to throw the exception if you catch the exception in your code. If you don't catch it, it gets passed along to the caller, which is why you would need the throws clause.

    0 讨论(0)
提交回复
热议问题