UNIT-5 Handling Error/Exceptions: Try Block
UNIT-5 Handling Error/Exceptions: Try Block
Handling Error\Exceptions
An exception is an event that occurs during execution of the program that disturbs normal flow
of the program instructions.
If the application contains exception then the program terminated abnormally then the rest of the
application is not executed.
1) try
2) catch
3) finally
4) throw
5) throws
Try block
The try block contains set of statements where an exception can occur. A try block is always
followed by a catch block, which handles the exception that occurs in try block. A try block must
be followed by catch blocks or finally block or both.
Syntax
Try
{
//statements that may cause an exception
}
Catch block
1. This is used for providing user friendly messages by catching system error messages.
2. In the catch we must declare an object of the appropriate execution class and it will be
internally
referenced JVM whenever the appropriate situation taking place.
Page 1
3. If we write ‘n’ number of catch’s as a part of JAVA program then only one catch will be
executing
at any point.
4. After executing appropriate catch block even if we use return statement in the catch block the
control never goes to try block.
Example-1 :-
Application without try-catch blocks
class Test
{
public static void main(String[] args)
{
System.out.println("Navthitiz");
System.out.println(10/0);
System.out.println("rest of the application");
}
}
E:\>java Test
Navthitiz
Exception in Thread “main” java.lang.ArithmeticException: / by zero
Handled by JVM type of the Exception description
In above example exception raised program is terminated abnormally & rest of the application is
not executed
Whenever the exception raised the default exception handler is responsible to handle the
exception & it is component of the JVM.
Page 2
a. If the catch block is matched then that block will be executed & rest of the application
executed & program is terminated normally.
b. If the catch block is not matched program is terminated abnormally.
class Test
{
public static void main(String[] args)
{
System.out.println("Navthitiz");
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println(10/2);
}
System.out.println("rest of the application");
}
}
In above example we are handling exception by using try-catch block hence the program is
terminated normally & rest of the application is executed.
Example-2 :-
Whenever the exception is raised in the try block JVM won’t terminate the program immediately
it will search corresponding catch block.
a. If the catch block is matched then that block will be executed & rest of the application
executed & program is terminated normally.
b. If the catch block is not matched program is terminated abnormally.
In below example catch block is not matched hence program is terminated abnormally.
class Error
{
public static void main(String[] args)
{
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
Page 3
System.out.println(100/2);
System.out.println(2+2);
System.out.println(100/0);
System.out.println(8-6);
System.out.println(9*3);
System.out.println(10);
}
}
Example 3:- If there is no exception in try block the corresponding catch blocks are not
checked.
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("Navthitiz");
System.out.println("Bardibash");
}
catch(NullPointerException e)
{
System.out.println(10/2);
}
System.out.println("rest of the application");
}
}
E:\sravya>java Test
Navthitiz
Bardibash
rest of the application
Finally block:
1. This is the block which is executing compulsory whether the exception is taking place or not.
2. This block contains same statements which releases the resources which are obtained in try
block (resources are opening files, opening databases, etc.).
3. Writing the finally block is optional.
Page 4
Finally block Syntax:-
try
{
risky code;
}
catch (Exception obj)
{
code to be run if the exception raised (handling code);
}
finally
{
Clean-up code;(database connection closing , streams closing……etc)
}
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
Example:
class TestTryCatch
{
public static void main(String[] args)
{
Page 5
try
{
Thread.sleep(10000);
System.out.println("hello");
}
catch(InterruptedException e)
{
}
}
}
exception in java:-
There are two types of exceptions in java checked exception , unchecked exception and error.
1) checked exception or compile time exception
2) unchecked exception or run time exception
There are two types of exceptions in java checked exception , unchecked exception and error.
1) checked exception:- A checked exception is an exception that is checked by the compiler at
compilation-time, these are also called as compile time exceptions.
Ex.
import java.io.*;
class CheckedException
{
public static void main(String[] args)
{
FileReader file = new FileReader("C://pankaj/file.txt");
BufferedReader fileInput = new BufferedReader(file);
fileInput.close();
}
}
Output:
C:\examples>javac CheckedException.java
CheckedException.java:7: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
FileReader file = new FileReader("C://pankaj/file.txt");
^
Page 6
CheckedException.java:12: error: unreported exception IOException; must be caught or declared
to be thrown
System.out.println(fileInput.readLine());
^
CheckedException.java:14: error: unreported exception IOException; must be caught or declared
to be thrown
fileInput.close();
^
3 errors
Example:
class ThrowsException
{
public static void main(String[] args)
{
Thread.sleep(25000);
System.out.println("hello");
}
}
Eg.
class UncheckedException
{
Throw keyword:-
1. It is used to handover user created Exception object to JVM.
2. It is used to throw exception explicitly.
Page 7
3. By using throw keyword it is possible throw predefined Exceptions & custom exception but it
is always recommended to throw custom exceptions
eg
withdraw(double amount)
{
If(amount>balance)
{
new throw InsufficientFundException();
}
}
Example:
import java.util.*;
class ThrowException
{
static int balance=50000;
static void withdraw(int amount)
{
if (amount>balance)
{
throw new ArithmeticException("Your Request not Accepted because of insufficient balance");
}
else
{
System.out.println("Your Request is Accepted");
System.out.println("Visit Once again");
}
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("please enter your Amount ");
withdraw(s.nextInt());
}
}
Page 8
Syntax
throw new exception_class("error message");
import java.util.*;
class Tests
{
static void validate(int age)
{
if (age<18)
{
throw new ArithmeticException("not eligible for vote");
}
else
{
System.out.println("welcome to the voting");
}
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
validate(s.nextInt());
System.out.println("Thank You");
}
}
throws keyword.
Handling Exception by using throws keyword
Eg.
import java.io.*;
class CheckedException
{
Page 9
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("C://pankaj/file.txt");
BufferedReader fileInput = new BufferedReader(file);
fileInput.close();
}
}
Example:
class ThrowsException
{
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(25000);
System.out.println("hello");
}
}
Error Exception
1. Error is a problem at runtime, for 1. Exception is a problem, for which, we
which we are unable to provide are able to provide solution
solutions programmatically. programmatically.
Ex: ArithmeticException
Ex: JVM internal Problem NullPointerException
StackOverFlowError ArrayIndexOutOfBoundsException
InSufficientMainMemory
Page 10
What are the differences between “throw” and “throws” keywords?
throw throws
1.”throw” keyword can be used to “throws” keyword will by pass the
rise the exceptions intentionally as exceptions from the present method
Per the application reqirement. to the caller method.
2.”throw” keyword will be utilized in “throws” keyword will be used in
method body. method declarations or in method
prototype (or) in method header
part.
3.”throw” keyword will allow only one “throws” keyword will allow more
exception class name. than one exception class name.
Page 11