Reputation: 4518
We can throw exception by try-catch
or throw
Scenario 1:
public void testMethod() throws MyException
{
throw new MyException();
}
Scenario 2:
public void testMethod() throws MyException
{
try
{
throw new MyException();
}
catch(MyException e)
{
throw e;
}
}
In the above code block
Upvotes: 2
Views: 1971
Reputation: 16039
Scenario 2 can only makes sense when you want to have code that will be executed when MyException
is thrown, e.g. you want to log that exception. If that is not the case then there is no point in adding a catch block and rethrowing the exception.
Upvotes: 4
Reputation: 496
Basically the need of throws is to intimate the compiler that the following code is expected to have a that type of exception such that to handle it if you want. In both scenarios it fully dependent upon the business needs because if the Exception of any Java Standard needs to be Wrapped in Custom Exception you need to handle it either by Wrapping around it as exception that has business explanation or to make a different execution based on parameters of the exception.
In scenario 2 there is no need to rethrow it untill it need to be explicitly throwed for any further code flow need to be executed instead of leaving it to complier. Hope this helps!
Upvotes: 2
Reputation: 1607
Usage for Scenario 2
Case 1: Get rid of checked exception i.e. throws MyException
clause and throwing a RuntimeException
instead,
Case 2: To log or call some Alert service etc. before re-throwing the exception up the stack
Upvotes: 0
Reputation: 126
If you want to throw a custom exception instead of actual exception then you should throw exception in catch but if you are throwing the same exception in catch them it is of no use.
Upvotes: 0
Reputation: 1019
Since you are throwing MyException you don't have to actually catch it and rethrow it unless you need to do some logging or any specific task in the catch.
But you still can have a catch blocks for other exceptions types and then wrap those exceptions with say MyException. This will give you a clear trace on the exception trail.
Eg:
public void doSomething() throws MyException {
try {
throw new MyException("Some Message");
}
catch(MyException e) {
// Only IF YOU NEED TO EXPLICITLY LOG IT OR HANDLE IT.
throw new MyException("A Message of failure",e)
}
catch(SomeOtherException e) {
// LOG or HANDLE IT.
throw new MyException("A Message of failure",e)
}
}
Upvotes: 0
Reputation: 24167
In scenario 2 you have the option to do some work
by catching it(e.g. wrapping it into your custom exception, do some book keeping etc.) before you throw it further. But if you do not process the exception and simply throw then IMO both are same.
Upvotes: 0