Exception Handlings Lecture Week 10
Topics Overview Advantages Types Examples
Overview Understand the following scenario Key in negative number as your ATM pin no. Withdraw money but not enough balance Use friend’s thumbprint Referring to to num[5] for array of size 5
Exception Handling Exception – unexpected error condition Not a usual/normal occurrence Whenever the program encounters runtime error – it will terminate abnormally What if the system is for the emergency room in hospital, air traffic control ??? Exception handling – ways to handle run time error so that your program can continue to run or stop gracefully
Examples
Example System.out.println(“Enter two numbers”); int no1 = in.nextInt(); int no2 = in.nextInt(); divNo = no1/no2; What if no2 =0? Then divNo = no1/0??? This will result a runtime error
Modified System.out.println(“Enter two numbers”); int no1 = in.nextInt(); int no2 = in.nextInt(); try { divNo = no1/no2; } catch (Arithmetic Exception ex) { System.out.println(“Attempt to divide by zero”); } try – block for normal operation catch – block for handling runtime error – normal flow is interrupted
Advantages Whenever there is an exception, The catch block will handles the exception Thus the program will nor terminate abruptly