Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
71 views

UNIT-5 Handling Error/Exceptions: Try Block

1) Exceptions are events that disrupt normal program flow, like divide-by-zero errors. 2) Try-catch blocks allow handling exceptions locally using catch blocks. Finally blocks contain cleanup code. 3) Exceptions are either checked, requiring handling, or unchecked, occurring at runtime. Throw explicitly throws exceptions, while throws indicates methods that may throw exceptions.

Uploaded by

aaush
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

UNIT-5 Handling Error/Exceptions: Try Block

1) Exceptions are events that disrupt normal program flow, like divide-by-zero errors. 2) Try-catch blocks allow handling exceptions locally using catch blocks. Finally blocks contain cleanup code. 3) Exceptions are either checked, requiring handling, or unchecked, occurring at runtime. Throw explicitly throws exceptions, while throws indicates methods that may throw exceptions.

Uploaded by

aaush
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

UNIT-5

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.

Exception handling key words:-

1) try
2) catch
3) finally
4) throw
5) throws

There are two ways to handle the exceptions in java.


1) By using try-catch block.
2) By using throws keyword.

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.

Exception handling by using Try –catch blocks:-


Syntax:-
try
{
exceptional code;
}
catch (ExceptionName reference_variable)
{
Code to run if an exception is raised (alternate code);
}

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.

Application with try-catch blocks:-


Whenever the exception is raised in the try block JVM won’t terminate the program immediately
it will search corresponding catch block.

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");
}

System.out.println("rest of the code...");


}
}

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);

for (int i = 0; i < 10; i++)


System.out.println(fileInput.readLine());

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");
}
}

2) Unchecked exception:- An unchecked exception is an exception that occurs at the time of


execution. It is also called as Runtime Exceptions. These include programming bugs, such as
logic errors.

Eg.

class UncheckedException
{

public static void main(String args[])


{
int num[] = {10,20,30,40,50,55,44,33,90,78};
System.out.println(num[10]);
}
}

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

What are purpose of using throw keyword:-


To hand over our created exception object to the jvm manually

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

The Java throw keyword is used to explicitly throw an exception.


throws keyword indicates what exception type may be thrown by a method.
There are many exception types available in Java: ArithmeticException,
ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.

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);

for (int i = 0; i < 10; i++)


System.out.println(fileInput.readLine());

fileInput.close();
}
}

Example:

class ThrowsException
{
public static void main(String[] args) throws InterruptedException
{

Thread.sleep(25000);
System.out.println("hello");
}
}

What is the difference between Error and Exception?

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

You might also like