Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, December 12, 2015

Is it a bad practice to catch Throwable?

Is it a bad practice to catch Throwable?


Is it a bad practice to catch Throwable?

For example something like this:

try {      // Some code  } catch(Throwable e) {      // handle the exception  }  

Is this a bad practice or we should be as specific as possible?

Answer by BalusC for Is it a bad practice to catch Throwable?


You need to be as specific as possible. Otherwise unforeseen bugs might creep away this way.

Besides, Throwable covers Error as well and that's usually no point of return. You don't want to catch/handle that, you want your program to die immediately so that you can fix it properly.

Answer by b.buchhold for Is it a bad practice to catch Throwable?


it depends on your logic or to be more specific to your options / possibilities. If there is any specific exception that you can possibly react on in a meaningful way, you could catch it first and do so.

If there isn't and you're sure you will do the same thing for all exceptions and errors (for example exit with an error-message), than it is not problem to catch the throwable.

Usually the first case holds and you wouldn't catch the throwable. But there still are plenty of cases where catching it works fine.

Answer by duffymo for Is it a bad practice to catch Throwable?


It's not a bad practice if you absolutely cannot have an exception bubble out of a method.

It's a bad practice if you really can't handle the exception. Better to add "throws" to the method signature than just catch and re-throw or, worse, wrap it in a RuntimeException and re-throw.

Answer by Brandon Yarbrough for Is it a bad practice to catch Throwable?


This is a bad idea. In fact, even catching Exception is usually a bad idea. Let's consider an example:

try {      inputNumber = NumberFormat.getInstance().formatNumber( getUserInput() );  } catch(Throwable e) {      inputNumber = 10; //Default, user did not enter valid number  }  

Now, let's say that getUserInput() blocks for a while, and another thread stops your thread in the worst possible way ( it calls thread.stop() ). Your catch block will catch a ThreadDeath Error. This is super bad. The behavior of your code after catching that Exception is largely undefined.

A similar problem occurs with catching Exception. Maybe getUserInput() failed because of an InterruptException, or a permission denied exception while trying to log the results, or all sorts of other failures. You have no idea what went wrong, as because of that, you also have no idea how to fix the problem.

You have three better options:

1 -- Catch exactly the Exception(s) you know how to handle:

try {      inputNumber = NumberFormat.getInstance().formatNumber( getUserInput() );  } catch(ParseException e) {      inputNumber = 10; //Default, user did not enter valid number  }  

2 -- Rethrow any exception you run into and don't know how to handle:

try {      doSomethingMysterious();  } catch(Exception e) {      log.error("Oh man, something bad and mysterious happened",e);      throw e;  }  

3 -- Use a finally block so you don't have to remember to rethrow:

 Resources r = null;   try {        r = allocateSomeResources();        doSomething(r);   } finally {       if(r!=null) cleanUpResources(r);   }  

Answer by DNA for Is it a bad practice to catch Throwable?


Catching Throwable is sometimes necessary if you are using libraries that throw Errors over-enthusiastically, otherwise your library may kill your application.

However, it would be best under these circumstances to specify only the specific errors thrown by the library, rather than all Throwables.

Answer by ic3 for Is it a bad practice to catch Throwable?


Throwable is the base class for all classes than can be thrown (not only exceptions). There is little you can do if you catch an OutOfMemoryError or KernelError (see When to catch java.lang.Error?)

catching Exceptions should be enough.

Answer by gawi for Is it a bad practice to catch Throwable?


Also be aware that when you catch Throwable, you can also catch InterruptedException which requires a special treatment. See Dealing with InterruptedException for more details.

If you only want to catch unchecked exceptions, you might also consider this pattern

try {     ...  } catch (RuntimeException exception) {    //do something  } catch (Error error) {    //do something  }  

This way, when you modify your code and add a method call that can throw a checked exception, the compiler will remind you of that and then you can decide what to do for this case.

Answer by Andrew Norman for Is it a bad practice to catch Throwable?


straight from the javadoc of the Error class (which recommends not to catch these):

 * An Error is a subclass of Throwable    * that indicates serious problems that a reasonable application    * should not try to catch. Most such errors are abnormal conditions.    * The ThreadDeath error, though a "normal" condition,   * is also a subclass of Error because most applications   * should not try to catch it.      * A method is not required to declare in its throws    * clause any subclasses of Error that might be thrown    * during the execution of the method but not caught, since these    * errors are abnormal conditions that should never occur.    *   * @author  Frank Yellin   * @version %I%, %G%   * @see     java.lang.ThreadDeath   * @since   JDK1.0  

Answer by CodeNewbie for Is it a bad practice to catch Throwable?


While it is generally bad practice to catch Throwable (as elucidated by the numerous answers on this question), the scenarios where catching Throwable is useful are quite common. Let me explain one such case that I use at my job, with a simplified example.

Consider a method that performs the addition of two numbers, and after successful addition, it sends an email alert to certain people. Assume that the number returned is important and used by the calling method.

public Integer addNumbers(Integer a, Integer b) {      Integer c = a + b;          //This will throw a NullPointerException if either                                   //a or b are set to a null value by the                                  //calling method      successfulAdditionAlert(c);      return c;  }    private void successfulAdditionAlert(Integer c) {      try {          //Code here to read configurations and send email alerts.      } catch (Throwable e) {          //Code to log any exception that occurs during email dispatch      }  }  

The code to send email alerts reads a lot of system configurations and hence, there could be a variety of exceptions thrown from that block of code. But we do not want any exception encountered during alert dispatch to propagate to the caller method, as that method is simply concerned with the sum of the two Integer values it provides. Hence, the code to dispatch email alerts is placed in a try-catch block, where Throwable is caught and any exceptions are merely logged, allowing the rest of the flow to continue.

Answer by Alireza Fattahi for Is it a bad practice to catch Throwable?


Although it is described as a very bad practice, you may sometimes find rare cases that it not only useful but also mandatory. Here are two examples.

In a web application where you must show a meaning full error page to user. This code make sure this happens as it is a big try/catch around all your request handelers ( servlets, struts actions, or any controller ....)

try{       //run the code which handles user request.     }catch(Throwable ex){     LOG.error("Exception was thrown: {}", ex);       //redirect request to a error page.    }  

}

As another example, consider you have a service class which serves fund transfer business. This method returns a TransferReceipt if transfer is done or NULL if it couldn't.

String FoundtransferService.doTransfer( fundtransferVO);  

Now imaging you get a List of fund transfers from user and you must use above service to do them all.

for(FundTransferVO fundTransferVO : fundTransferVOList){     FoundtransferService.doTransfer( foundtransferVO);  }  

But what will happen if any exception happens? You should not stop, as one transfer may have been success and one may not, you should keep go on through all user List, and show the result to each transfer. So you end up with this code.

for(FundTransferVO fundTransferVO : fundTransferVOList){      FoundtransferService.doTransfer( foundtransferVO);   }catch(Throwable ex){      LOG.error("The transfer for {} failed due the error {}", foundtransferVO, ex);    }  }  

You can browse lots of open source projects to see that the throwable is really cached and handled. For example here is a search of tomcat,struts2 and primefaces:

https://github.com/apache/tomcat/search?utf8=%E2%9C%93&q=catch%28Throwable https://github.com/apache/struts/search?utf8=%E2%9C%93&q=catch%28Throwable https://github.com/primefaces/primefaces/search?utf8=%E2%9C%93&q=catch%28Throwable


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 71

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.