ExceptionHandling
ExceptionHandling
Exception Handling
Chapter Topics
Chapter 10 discusses the following main topics:
⚫ Exception Handling Fundamentals
⚫ Exception Types
⚫ Using try-catch
⚫ throw
⚫ throws
⚫ finally
Exception
⚫ An exception is an object that is generated as the result of
an error
⚫ Exceptions are said to be thrown
⚫ Programmer should handle the exception
⚫ Unhandled exceptions will crash a program
⚫ Java exceptions are handled using 5 keywords try, catch,
throw, throws and finally.
Exception Types
Exception Types
Exception Types
Using try-catch
⚫ Try- Statements that you want to monitor for exceptions
are contained within try
⚫ Catch – The exception is handled in catch block.
try Class Ex
{
{ public static void main(String [] args)
{
} int d = 0;
try
catch(ExceptionType exob) {
{ int res =45/d;
}catch(ArithmeticException ae)
{
} System.out.println(“division by
zero” + ae);
}
}
}
throw throw – To manually throw an exception using keyword throw
}
throw Vs throws
finally
finally –Any code absolutely must be executed after try block is put in finally
block. Java finally block is always executed whether expression is handled or
not. It follows try/catch block.
Finally Example
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Try
Write a program to create a class test, which contains a method
check_number() that takes number as a parameter and check if the
number is less than 1. If so, it must throw an ArthimeticException
otherwise find the square of that number.