0% found this document useful (0 votes)
7 views28 pages

Java Exception Handling Explained

The document outlines the three types of errors in Java programs: compile-time errors, run-time errors, and logical errors, along with examples for each. It explains exception handling in Java, including the hierarchy of exceptions, checked vs. unchecked exceptions, and the use of try-catch-finally blocks for managing exceptions. Additionally, it describes the throw and throws keywords for handling exceptions and the creation of custom exceptions.

Uploaded by

Aswin Gouda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views28 pages

Java Exception Handling Explained

The document outlines the three types of errors in Java programs: compile-time errors, run-time errors, and logical errors, along with examples for each. It explains exception handling in Java, including the hierarchy of exceptions, checked vs. unchecked exceptions, and the use of try-catch-finally blocks for managing exceptions. Additionally, it describes the throw and throws keywords for handling exceptions and the creation of custom exceptions.

Uploaded by

Aswin Gouda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Errors in a java program:-

There are basically 3 types of errors in a java program.


1. Compile time errors
2. Run time errors
3. Logical errors
Compile time errors:-
These are syntactical errors found in the code due to which a program fails to compile.
Ex:- forgetting a semicolon or forgetting to close brackets etc.
Ex:-
class erroe
{
Public static void main(String[] args)
{
[Link](“hello”)
}
}
Note:- we have missed a semicolon so during compilation we will get an error.
Run time errors:-
These errors represent inefficiency of the computer system to execute a particular program.
Ex:- insufficient memory
class Err
{
Public static void main()
{
[Link](“hello”);
}
}
Note:-
During compilation we will not get any error but during runtime we will get the arror i.e
Exception in thread main [Link]: main

Runtime errors are not detected by the java compiler they are detected by jvm only at
runtime.
Logical Errors:-
When there is an error in the logic of the program like programmer might be using wrong
formula.
Logical errors are not detected by either compiler or jvm.
Exception:-
An unwanted unexpected situation which corrupts the normal flow of execution in java is
called as exception.
Or simply it is a runtime error.
Or it is an object which is thrown at runtime.

An exception can occur for many reasons. Some of them are:

Invalid user input


Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Java Exception hierarchy:-

▪ Throwable class is the root class in the hierarchy.


▪ hierarchy splits into two branches: Error and Exception.
▪ Errors
▪ Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out
of memory, memory leaks, stack overflow errors, library incompatibility, infinite
recursion, etc.
▪ Errors are usually beyond the control of the programmer and we should not try to handle
errors.
Types of Java Exceptions:-
There are mainly two types of exceptions: checked and unchecked
An error is considered as the unchecked exception.
Difference between Checked and Unchecked Exceptions:-
Checked Exception:-
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
Unchecked Exception:-
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
Common Scenarios of Java Exceptions:-
1. A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2. A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
[Link]([Link]());//NullPointerException
3. A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException
Runtime Stack Mechanism:-
1. For every thread or method jvm will create a runtime stack.
2. For each and every method call performed by that thread one entry will be added into
the corresponding stack.
3. This entry is called activation record or stackframe.
4. After completing every method call the corresponding entry from the stack will be
removed.
5. After completing all method calls the stack will become empty. And the empty stack
will be destroyed by jvm just before terminating the thread.
Ex:-
Class Test
{
Public static void main(String[] args)
{
doStuff();
}
Public static void doStuff()
{
doMoreStuff();
}
Public static void doMoreStuff()
{
[Link](“hello”);
}
}
}
Default Exception Handling in java:-
▪ If an exception raised, the method in which it's raised is responsible for the creation of
Exceptions object by including the following information:

▪ Name of the Exception


▪ Description of the Exception
▪ Stack Trace(Location of exception)
▪ After creating Exception object the method handovesr it to the JVM.
▪ JVM checks for Exception Handling code in that method.
▪ If the method doesn't contain any Exception handling code then JVM terminates the
method abnormally and removes the corresponding entry from the stack.
▪ JVM identify the caller method and checks for Exception Handling code in that method. If
the caller doesn't contain any exception handling code then JVM terminates that method
abnormally and removes the corresponding entry from the stack.
▪ This process will be continue until main() method.
▪ If the main() method also doesn't contain exception handling code the JVM terminates
that main() method and removes the corresponding entry from the stack.
▪ Just before terminating the program abnormally JVM handovers the responsibility of
exception handling to the Default Exception Handler which is the component of
JVM.

▪ Default Exception Handler just print exception information to the consol in the following
format

▪ Name of Exception: Description

▪ Stack Trace (Location of the Exception)


Ex:-
“Exception in thrad “xxx” Name of Exception: Description
Location of Exception(Stack trace)”
Ex:-
Class Test
{
Public static void main(String[] args)
{ o/p:-
doStuff(); Exception in thread “main”
} [Link]:/ by
Public static void doStuff() zero
{
doMoreStuff(); At [Link]()
} At [Link]()
Public static void doMoreStuff() At [Link]()
{
[Link](10/0);
}
}}
Customized /User Defined Exception handling in java:-
Exceptions can be tackled by the programmer by carefully designing the program.
Steps for handling exceptions in java:-
Step 1:-
The programmer should observe the statements in his program where there may be a
possibility of exceptions.
Such statements should be kept inside try block.
Syntax:-
try
{
Statements;
}
Step 2:-
The programmer should write the catch block where he should display the exception details to
the user.
The programmer should also display a message regarding what can be done to avoid this error.
Syntax:-
catch(Exceptionclass ref)
{
Statements;
}
Note:-
We can display the exception details using any one of the following ways.
1. Using print() or println() such as [Link](ref);
2. Using printStackTrace() method of Throwable class, which fetches the details from the
exception stack and display them.
3. Lastly programmer can use a block finally to perform any cleanup code like closing file
etc.
Finally block:-

Syntax:-
finally
{
Statements;
}
1. The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception.
2. The main objective of finally block is to maintain cleanup code.
3. The specialty of finally block is it will be executed always irrespective of whether
exception is raised or not .
Ex:-
try
{
Risky code;
}
catch(Exception e)
{
Handling code;
}
finally
{
Cleanup code
}
Java Exception Handling Example:-
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
//rest code of the program
[Link](“this is an example of exception");
}
}
o/p:- Exception in thread main [Link]:/ by zero
rest of the code...
this is an example of exception
Throw statement/clause:-
❑ Sometimes we can create Exception object explicitly and we can handover that object to
jvm manually.
❑ For this purpose we have to use throw keyword.
Syntax:-
throw new ArithmaticException(“/by zero”);

We are handovering our created We are creating exception object


Exception to jvm manually. Explicitly.
❑ Hence the main objective of throw keyword is to handover our created exception object to
jvm manually.
Ex:-
class Test
{
Psvm(String[] args)
{
Throw new ArithmaticException(“/ by zero”);
}}
throws clause/keyword:-
1. In our program if there is any chance of raising checked exception, compulsory we should
handle either by try catch block.
2. Or else if being a programmer you don’t want to handle the checked exceptions you should
throw them out using throws clause.
Ex:-
import [Link].*;
class Sample{
Private String name;
void accept()
{
InputStreamReader obj=new InputStreamReader([Link]);
BufferReader br=new BufferReader(obj);
[Link](“enter your name : “);
Name=[Link]();
}
void display()
{ [Link](“Name: “+name);}
Class Ex1
{
Public static void main(String[] args)
{
Sample s=new Sample();
[Link]();
[Link]();
}
}
Note:- readLine() method of BufferReader class throws IoException and which is a checked
exception.
So either we should handle it by the help of try catch block otherwise we have to use throws
keyword.

o/p:-unreported exception [Link]; must be caught or declared to be


thrown.
name=[Link]();
^
Since it was a checked exception we should throw it out of the method using throws clause.

i.e The throws clause is written at the side of accept() method since in this method the
readLine() is called also we should write throws clause next to main() method since in this
method the accept() is called.
Ex:-Ex:-
import [Link].*;
class Sample{
Private String name;
void accept() throws IOException
{
InputStreamReader obj=new InputStreamReader([Link]);
BufferReader br=new BufferReader(obj);
[Link](“enter your name : “);
Name=[Link]();
}
void display()
{ [Link](“Name: “+name);}
Class Ex1 throws IOException
{
Public static void main(String[] args)
{
Sample s=new Sample();
[Link]();
[Link]();
}
}

o/p:-enter name: Subhasmita


Name: Subhasmita
Note:- (Use of different keywords in exception)
try:- To maintain risky code.
Catch:-To maintain exception handling code.
Finally:- To maintain cleanup code.
Throw:- To handover our created exception object manually to jvm.
Throws:- To delegate the responsibility of exception handling to the caller.

Customized or User defined Exceptions:-


▪ we can create our own exceptions that are derived classes of the Exception class.
▪ Creating our own Exception is known as custom exception or user-defined exception.
▪ Basically, Java custom exceptions are used to customize the exception according to user
need.
o/p:-
1001Raja Rao 10000.0
1002 Rama Rao 12000.0
1003 Subba Rao 5600.5
MyException:Balance amount is less
At [Link]([Link]

You might also like