-1

When should we chose to throws an exception?

 public Something sqlQuery(String sqlQuer) throws SqlException {

 }

We can catch this exception in try catch.

In which situation does we choose to use throws instead of catching immediately? is it some design pattern related?

fatherazrael
  • 5,511
  • 16
  • 71
  • 155
  • Do you understand what an Exception is? It is an "abnormal termination of an application". Can your system recover from the error, and keep on working? catch it. can't it? throw. – Stultuske Nov 05 '19 at 07:56
  • 1
    Handle an exception if you can do something reasonable as a result of that exception. Otherwise, just let callers decide what to do with it. – Andy Turner Nov 05 '19 at 08:36

1 Answers1

0

If a method (M1) has the capability to handle an exception by itself, then use try-catch-finally. If not, throw it. The calling method (M2) now has to handle a potential exception of M1 or throw it itself.

Beside of this, all Expections expect of RuntimeExceptions require to be catched.

Lecagy
  • 489
  • 2
  • 10