-1

I have a method which uses java.util.Date and java.util.Calendar objects to give me current time with timezone and one of my colleague recommended to add try catch with Exception e to catch. But when I searched on google about any exception thrown with the inbuild methods of these classes I don't find any.

Do I still need to wrap the code with try and catch??? Is try catch required for the block as simple as below:

try{
    Date dto = Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dto);
    String dateString = calendar.getTime().toString();
    return dateString;  
}catch(Exception e){
    e.getMessage();
}
freedev
  • 25,946
  • 8
  • 108
  • 125
Prakruti Pathik
  • 392
  • 4
  • 17
  • 2
    No, it's not... – Thomas Ayoub Mar 17 '17 at 23:05
  • @ThomasAyoub: Can you explain in little detail? – Prakruti Pathik Mar 17 '17 at 23:06
  • 2
    maybe showing your code can make it easier for people to analyse your question at hand? – Ousmane D. Mar 17 '17 at 23:06
  • 5
    **DO NOT EVER** add try-catch code like that. You're ignoring the exception. Actually, you probably can't add code like that, because compiler will complain about missing return statement. Just remove the try-catch. You should only add try-catch when you're interested in a particular exception, or if you truly want code to continue to execute even if an error occurs, in which case you need to know how to continue from an error state. – Andreas Mar 17 '17 at 23:13
  • Possible duplicate of [When to catch the Exception vs When to throw the Exceptions?](http://stackoverflow.com/questions/18679090/when-to-catch-the-exception-vs-when-to-throw-the-exceptions) – Thomas Ayoub Mar 17 '17 at 23:15
  • @Andreas: Thankyou.. that explains the case.. – Prakruti Pathik Mar 17 '17 at 23:24

1 Answers1

0

In Java, Exception and Error classes are inherited from Throwable class. Exception and Error classes has subclasses.

If your code throw an Exception (except RunTimeException) you must catch this exception. But If your code throw an RunTimeException or Error you must rewrite your code which doesn't throw RunTimeException or Error.

Throwable, Exception and Exception subclasses (except RunTimeException) are checked Exception, so you have to catch this exceptions.

But RunTimeException and Error classes are unchecked Exceptions, so you must rewrite your code which doesn't throw RunTimeException or Error.

Mustafa Çil
  • 766
  • 8
  • 15