Exception Handling
Exception Handling
Exception Handling
errors are:
1. Divide by zero
arithmetic operation.
accessed with an illegal index. The index is either negative or greater than or equal
not open.
variable) specified
indicate that an index is either negative or greater than the size of the string
when the method receives an argument which is not accurately fit to the given
handled in the code itself with the help of try catch block.
java.lang.RuntimeException class.
Syntax of exception handling code
• Java try and catch
• The try statement allows you to define a block of code to be tested for errors
while it is being executed.
• The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
• The try and catch keywords come in pairs:
• Syntax
• try
• {
• // Block of code to try
• }
• catch(Exception e)
• {
• // Block of code to handle errors
• }
• // Java program to demonstrate ArithmeticException
• class ArithmeticException_Demo
• {
• public static void main(String args[])
• {
• try {
• int a = 30, b = 0, c = 5;
• int c = a/b; // cannot divide by zero
• System.out.println ("Result = " + c);
• }
• catch(ArithmeticException e) {
• System.out.println ("Can't divide a number by 0");
• }
• int y = a / c;
• System.out.println (“y = “ + y);
• }
• }
• //Java program to demonstrate NullPointerException
• class NullPointer_Demo
• {
• public static void main(String args[])
• {
• try {
• String a = null; //null value
• System.out.println(a.charAt(0));
• }
• catch(NullPointerException e)
• {
• System.out.println("Null Pointer Exception..");
• }
• }
• }
• public class Demo1
• {
• public static void main(String[ ] args)
• {
• try
• {
• int[] myNumbers = {1, 2, 3};
• System.out.println(myNumbers[10]);
• }
• catch (ArrayIndexOutOfBoundsException e)
• {
• System.out.println(“Array is out of bound.");
• }
• }
• }
Multiple catch statements
• public class MultipleCatchBlock1
• {
• public static void main(String[] args) {
• int a[ ] = { 5 , 10 } , b = 5;
• try{
• int x = a[2] / b - a[1];
• }
• catch(ArithmeticException e)
• {
• System.out.println(“Division by zero");
• }
Multiple catch statements
• catch(ArrayIndexOutOfBoundsException e)
• {
• System.out.println(“Array index error");
• }
catch(ArrayStoreException e)
• {
• System.out.println(“Wrong data type");
• }
• int y = a[1] / a[0];
• System.out.println(“y= “ + y);
• }
• }
Using Finally statement
• The finally statement lets you execute code, after try...catch,
regardless of the result:
• public class Demo2
• {
• public static void main(String[ ] args)
• {
• try {
• int[] myNumbers = {1, 2, 3};
• System.out.println(myNumbers[10]);
• }
• catch (ArrayIndexOutOfBoundsException e) {
• System.out.println(“Array is out of bound.");
• }
• finally {
• System.out.println("The 'try catch' is finished.");
• }
• }
• }