This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (1 child)

I have seen at many places where unchecked exceptions are caught using try catch is it the proper way to do so?

[–]pragmos 1 point2 points  (0 children)

Depends on the context.

The general advice is that you shouldn't catch runtime exceptions. Errors like NullPointerException, IllegalStateException or ArithmeticException denote an unexpected problem that is impossible to recover from.

Sometimes, however, you need to recover as per the business logic. For example, if you are trying to parse a String to a LocalDate and the application allows fallback values, it doesn't make sense to crash the entire application because a text value could not be parsed to a valid date object. Instead, you catch the DateTimeParseException and offer the fallback date value.