Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between rethrowing a caught exception immediately and a throws declaration [duplicate]

Tags:

java

exception

public void init() throws SocketException
{
    try
    {
        socket = new DatagramSocket(4446);
    }
    catch (SocketException se)
    {
        throw se;
    }
}

and

public void init() throws SocketException
{
    socket = new DatagramSocket(4446);
}
  • Are the two chunks of code essentially the same or are they different in behavior to a caller who calls this init method?
  • Will the exception received by caller of this method have same information and exactly same stack trace?
like image 396
Ahmed Avatar asked Dec 07 '25 10:12

Ahmed


2 Answers

The stack trace you will get will be exactly the same as can easily be proved by a simple experiment. In terms of code execution, there will be extra handling of the exception in the first example, but no significant difference in behaviour

If the deeper exception needs to be caught, it would be more usual to wrap the exception or exceptions in a new exception with the original exception used as an argument, in which case you will get two stack traces - one from init() and one from the original exception.

throw new RuntimeException(se);
like image 131
Neil Masson Avatar answered Dec 13 '25 09:12

Neil Masson


from the callers point of view they are same, caller must either catch SocketException or add throws SocketException.

The only issue is that in some case calling method may not be allowed to use throws in declaration as SocketException is a checked exception.

Will the exception received by caller of this method have same information and exactly same stack trace ?

yes, because your not throwing a new exception from init().

like image 29
Ramanlfc Avatar answered Dec 13 '25 08:12

Ramanlfc