3
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?
randers
  • 5,031
  • 5
  • 37
  • 64
Ahmed
  • 14,503
  • 22
  • 92
  • 150
  • 3
    Not really a dupe. Stack trace info will be identical and caller won't be able distinguish between either implementation. The first implementation should be avoided as redundant and of unclear intent. – pvg Dec 27 '15 at 16:30
  • Yes, they behave identical since rethrowing isn't changing the exception at all: http://ideone.com/uymH8u - you're merely "inspecting" the exception and then pass the original onwards. – zapl Dec 27 '15 at 16:45

3 Answers3

2

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);
Neil Masson
  • 2,609
  • 1
  • 15
  • 23
2

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().

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
1

There is not differences at all, but sometimes, if a process fail, you want to add some logic before rethrowing the exception (like closing a connection).

public void init() throws SocketException {
    try {
        socket = new DatagramSocket(4446);
    } catch (SocketException se) {
        // damn, it failed, lets do something before throwing.
        throw se;
    }
}



And as @Ramanlfc pointed out, sometime you implement an interface and cannot throw checked Exception.

@Override
public void init() {
    try {
        socket = new DatagramSocket(4446);
    } catch (SocketException e) {
        throw new RuntimeException("Failed to create DatagramSocket on port 4466", e);
    }
}

Here we encapsulate the exception and we are adding another level in the stackstrace.

Anthony Raymond
  • 7,434
  • 6
  • 42
  • 59