-1

In main, I have to call some methods in this order:

 try {
        instance.method1()
    } catch (SecurityException | IOException e) {
        e.printStackTrace();
    }

// Other methods...

try {
    instance.method2
} catch (XMLStreamException | IOException e) {
    e.printStackTrace();
}

// Other methods...

try {
     instance.method3
} catch (XMLStreamException | IOException e) {
    e.printStackTrace();
}

The question is: Is better to handle the methods in different try-catch statments, or all methods in one handler, as below?

try {
     instance.method1
     instance.method2
     instance.method3
    } catch (XMLStreamException | IOException | SecurityException e) {
        e.printStackTrace();
    }
Nelly Junior
  • 556
  • 2
  • 10
  • 30
  • a) if you only call `e.printStackTrace()`, why even bother to catch the execption? b) you could simply write multiple `catch`-blocks and act accordingly in each (in case you want to do something more sensible than just printing the stacktrace) – Turing85 Jul 13 '15 at 20:36

3 Answers3

1
try {
 instance.method1
 instance.method2
 instance.method3
} catch (XMLStreamException e){

} catch (SecurityException e){

} catch (IOException e){

}

All methods in one try block. This way you can handle specific exception in separate catch block

Endrju
  • 46
  • 1
  • 3
0

It depends if you want to continue indepently on previous statements:

try {
    instance.method1
    instance.method2
    instance.method3
} catch (XMLStreamException | IOException | SecurityException e) {
    e.printStackTrace();
}

When instance.method1 fails, method2 and method3 wont be executed, in separated case there will be executed all

maskacovnik
  • 3,080
  • 5
  • 20
  • 26
-1

It's not really better or worse honestly. Unless you are doing something other than printing the stack trace where it necessitates doing something specific from that error then you would want to separate it. I prefer the last option since it is more readable.

mumfy
  • 154
  • 1
  • 12