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 show you 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:
try{ // do business logic }catch(ExceptionType1 e){ // handle Exception code, such as: logging info for debug } |
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.
try{ // do business logic }catch(ExceptionType1 e){ // code for handling business logic with ExceptionType1 }catch(ExceptionType2 e){ // code for handling business logic with ExceptionType2 }catch(ExceptionType3 e){ // code for handling business logic with ExceptionType3 } |
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:
try{ // do business logic }catch(ExceptionType1 e){ // code for handling Exception with ExceptionType1 }catch(ExceptionType2 e){ // code for handling Exception with ExceptionType2 }finally{ // final code segment } |
or
try{ // do business logic }finally{ // final code segment } |
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
try { customerService.postCustomer("", 10); } catch (InValidNameException e) { System.out.println(e.getMessage()); } catch (InValidAgeException e) { System.out.println(e.getMessage()); } finally { System.out.println("Done!"); } |
Output:
Please check Name again for valid! Done! |
– If we try to post a customer object has invalid age=-1, it will be throw an Exception
InValidAgeException
try { customerService.postCustomer("Jack", -1); } catch (InValidNameException e) { System.out.println(e.getMessage()); } catch (InValidAgeException e) { System.out.println(e.getMessage()); } finally { System.out.println("Done!"); } |
Output:
Please check Age again for valid! Done! |
Java 7 & try/catch handling
For multi catch bock, Java 7 supports a new syntax:
try{ // do business logic }catch(ExceptionType1 | ExceptionType2 e){ // code for handling Exception }finally{ // special code segment } |
Sample:
try { customerService.postCustomer("", 10); } catch (InValidNameException | InValidAgeException e) { System.out.println(e.getMessage()); } finally { System.out.println("Done!"); } // for Checked Exception try { customerService.postCustomer("Jack", -1); } catch (InValidNameException | InValidAgeException e ) { System.out.println(e.getMessage()); } finally { System.out.println("Done!"); } |
Output:
Please check Name again for valid! Done! Please check Age again for valid! Done! |
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:
try (BufferedReader br = new BufferedReader(new FileReader("C://readfile/input.txt"))) { String line; while (null != (line = br.readLine())) { // processing each line of file System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } |
II. throw/ throws keywords
throw & throws are 2 keywords with difference purposes in Java Exception.
– throw is used to create a new Exception, sample:
if (name.isEmpty()) { throw new InValidNameException("Please check Name again for valid!"); } if (age > 150 || age < 1) { throw new InValidAgeException("Please check Age again for valid!"); } |
– throws is used to postpone an UnCheckedException. With CheckedException we don’t need throws, sample:
public void postCustomer(String name, int age) throws InValidAgeException, InValidNameException { // check then throw exception if invalid info if (name.isEmpty()) { throw new InValidNameException("Please check Name again for valid!"); } if (age > 150 || age < 1) { throw new InValidAgeException("Please check Age again for valid!"); } custStorage.put(name, new Customer(name, age)); } |
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?
public Customer findCustomerById(String name) { Customer cust = custStorage.get(name); if (null == cust) { throw new CustomerNotFoundException("Customer Not Found!"); } return cust; } |
CustomerNotFoundException is UnCheckedException, So we don’t need to use throws keyword.
III. Full Sourcecode
package com.javasampleapproach.customizedexception; import java.util.HashMap; import java.util.Map; public class CustomerService { Map<String, Customer> custStorage = new HashMap<String, Customer>(); public CustomerService() { Customer peter = new Customer("Peter", 20); Customer jack = new Customer("Jack", 30); custStorage.put("peter", peter); custStorage.put("jack", jack); } public Customer findCustomerById(String name) { Customer cust = custStorage.get(name); if (null == cust) { throw new CustomerNotFoundException("Customer Not Found!"); } return cust; } public void postCustomer(String name, int age) throws InValidAgeException, InValidNameException { // check then throw exception if invalid info if (name.isEmpty()) { throw new InValidNameException("Please check Name again for valid!"); } if (age > 150 || age < 1) { throw new InValidAgeException("Please check Age again for valid!"); } custStorage.put(name, new Customer(name, age)); } public static void main(String[] args) { CustomerService customerService = new CustomerService(); // for Checked Exception try { customerService.postCustomer("", 10); } catch (InValidNameException | InValidAgeException e) { System.out.println(e.getMessage()); } finally { System.out.println("Done!"); } // for Checked Exception try { customerService.postCustomer("Jack", -1); } catch (InValidNameException | InValidAgeException e) { System.out.println(e.getMessage()); } finally { System.out.println("Done!"); } // Unchecked Exception will be throwed after executing findCustomerById("Mary") customerService.findCustomerById("Mary"); } } |
Output:
Please check Name again for valid! Done! Exception in thread "main" Please check Age again for valid! Done! com.javasampleapproach.customizedexception.CustomerNotFoundException: Customer Not Found! at com.javasampleapproach.customizedexception.CustomerService.findCustomerById(CustomerService.java:19) at com.javasampleapproach.customizedexception.CustomerService.main(CustomerService.java:58) |
Last updated on March 21, 2019.