How to handle Java Exception

We had introduced JavaException in 2 articles: Understand Java Exception & The effect to Java Program (Single & Multi Thread) & How to work with Java Custom Exception. In the tutorial, JavaSampleApproach will guide how to handle Java Exception.
Related post:
How to use Spring Exception Handler for SpringMVC: @ExceptionHandler, @ResponseStatus, @ControllerAdvice

I. try/catch statement

For handling Exception, Java provides try/catch statement:

Java also supports for multi catch blocks base on Exception Type. The solution helps us a lot for handling business logic with each kind of Exception.

When do business logic code makes an exception, If the exception has type ExceptionType1, code for handling business logic with ExceptionType1 will be executed. If the exception has type ExceptionType2, code for handling business logic with ExceptionType2 will be executed. If the exception has type ExceptionType3, code for handling business logic with ExceptionType3 will be executed.

finally keyword is a solution for executing a special code segment when having Exception or Not. finally block format:

or

The block final code segment always be executed.
Sample:
– If we try to post a customer object with empty name, it will be throw an Exception InValidNameException

Output:

– If we try to post a customer object has invalid age=-1, it will be throw an Exception
InValidAgeException

Output:

Java 7 & try/catch handling

For multi catch bock, Java 7 supports a new syntax:

Sample:

Output:

Java 7 provides a new approach for closing resources with clean & clear code by try-with-resources statment, detail at: Java 7 – try-with-resources Statement
Sample:

II. throw/ throws keywords

throw & throws are 2 keywords with difference purposes in Java Exception.
throw is used to create a new Exception, sample:

throws is used to postpone an UnCheckedException. With CheckedException we don’t need throws, sample:

InValidAgeException, InValidNameException are CheckedException, so we need throws it for oostponement.
public void postCustomer(String name, int age) throws InValidAgeException, InValidNameException
How about below function?

CustomerNotFoundException is UnCheckedException, So we don’t need to use throws keyword.

III. Full Sourcecode

Output:

HandleJavaException


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*