2

I have question on Java throw exception at class method definition:

public void someMethod () throws SomeException {
 try{
   ...
 }catch (SomeException e ){
   ....
 }
}

When we declare throw SomeException at the method declaration, do we still have to try/catch in the body or, can we just use throw new SomeException like this:

public void someMethod () throws SomeException {
  // do something
  throw new SomeException() ;
}

what is the correct way to throw exception when we have throw Exception at the method declaration.

1
  • You can test it by writing code and compiling it. By the way think of what does it mean to declare throws clause in method signature? Commented Dec 21, 2013 at 14:36

2 Answers 2

5

No, you do not need to catch the exception that you throw as long as you're not changing it or selectively throwing it only in some situations when the exception occurs. So this is often perfectly fine:

public void someMethod () throws SomeException {
  // do something
  throw new SomeException() ;
}

Although it's often good to give your SomeException class a constructor that takes a String parameter, and then pass that String to the super constructor to allow your exception to be able to pass more information through.

Sign up to request clarification or add additional context in comments.

Comments

1

Your prototype public void someMethod () throws SomeException is mandating that someMethod will only throw exceptions of type SomeException. (Or any exception classes derived from SomeException).

Therefore you do not need to catch that particular exception in your function, but you will need to catch all others.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.