質問

Suppose I have a method or a constructor that uses another method or constructor internally that declares a RuntimeException can be thrown.

// Example:
public MyClass(Object arg) {
    setVar(arg);
    // Not responsible for dealing with the exception
}

public void setVar(Object arg) throws MyRuntimeException {
    if(!isValidArg(arg))
        throw new MyRuntimeException("Got you, evil argument!");
    // Do something
}

In this case the RuntimeException is thrown if for example necessary preconditions are not fulfilled.

Q: Should the wrapping method/constructor declare the same Exception, if it's argument could cause the Exception to be thrown?

役に立ちましたか?

解決

It really depends on the context that the code is in. If you want to make something that is self contained, like a Library, you might want to catch the Exception inside the class, just to make the use of your code cleaner.

However if you're making code as part of a project, then I would, as you say, "carry the throws exception" until it doesn't make sense, semantically.

他のヒント

I would declare it if it is not supposed to be handled inside the wrapping method - the same as with checked exceptions.

Anyway good to have such a hint for method even for unchecked exceptions. The client will decide if it needs to be handled.

RuntimeExceptions are thrown without the need to include it in the throws signature for neither of the methods.

You should read this about runtime exception

no, Runtime Exceptions are not checked i.e. compiler does not forces you to deal with them. But as a good programming practice you can handle the exception like

public MyClass(Object arg) {
  try{
    setVar(arg);
}
catch(MyRuntimeException exp){
   // code if exception arises
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top