0% found this document useful (0 votes)
13 views68 pages

Java Exception Handling Overview

The document provides a comprehensive overview of exception handling in Java, detailing its importance in maintaining the normal flow of applications by managing runtime errors. It categorizes exceptions into checked and unchecked types, explains the use of try-catch blocks, and discusses the significance of the throw and throws keywords for exception propagation. Additionally, it covers threading concepts, synchronization, and the lifecycle of threads, emphasizing the need for thread management in Java applications.

Uploaded by

wofig21729
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)
13 views68 pages

Java Exception Handling Overview

The document provides a comprehensive overview of exception handling in Java, detailing its importance in maintaining the normal flow of applications by managing runtime errors. It categorizes exceptions into checked and unchecked types, explains the use of try-catch blocks, and discusses the significance of the throw and throws keywords for exception propagation. Additionally, it covers threading concepts, synchronization, and the lifecycle of threads, emphasizing the need for thread management in Java applications.

Uploaded by

wofig21729
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

Exceptions

• The Exception Handling in Java is one of the


powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.
• Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the
normal flow of the program. It is an object which is
thrown at runtime.
Advantages
• The core advantage of exception handling is to maintain
the normal flow of the application. An exception normally
disrupts the normal flow of the application that is why we
use exception handling. Let's take a scenario:
line 1;
line 2;
line 3;
line 4;
line 5;//exception occurs
line 6;
line 7;
line 8;
Cont..
• Suppose there are 8 line in your program and there
occurs an exception at line 5, the rest of the code will
not be executed
• i.e. line 6 to 8 will not be executed. If we perform
exception handling, the rest of the statement will be
executed.
• That is why we use exception handling in java.
Exception Types
System Errors
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

System errors are thrown by JVM LinkageError Several more classes

and represented in the Error class.


The Error class describes internal VirtualMachineError

system errors. Such errors rarely Error

occur. If one does, there is little AWTError

you can do beyond notifying the


user and trying to terminate the Several more classes

program gracefully.
Exceptions
Exception describes errors
caused by your program ClassNotFoundException
and external
circumstances. These IOException
errors can be caught and ArithmeticException
handled by your program. Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


Runtime Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError RuntimeException is caused by


Error programming errors, such as bad
casting, accessing an out-of-bounds
AWTError
array, and numeric errors.

Several more classes


Types of Exceptions
• Errors - serious and fatal problems
• Exceptions - can be thrown by any program, user can
extend
• RuntimException - caused by illegal operations,
thrown by JVM (unchecked)
Types of Exceptions
Checked Exception
Checked Exception
The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions
e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
Exception Cause of Creation

ClassNotFoundExcepti Is thrown when the Java Run-time system is unable to find referred class
on

IllegalAccessException Is thrown when you refer an object, class, variable, constructor or a


method that is not accessible

InstantiationException Is thrown when you to create an instance of a class by using the


newInstance() Method, but the referred class cannot be instantiated

NoSuchMethodExcepti Is thrown when a particular method cannot be found


on
Unchecked Exception
Unchecked Exception
• The classes which inherit RuntimeException are
known as unchecked exceptions
Exception Cause of Creation
ArithmeticException Occurs when you make an arithmetic err, such as dividing a number by zero

ArrayIndexOutOfBoundsException Occurs when an attempt is made to access an array element beyond the index of the array

ArrayStoreException Occurs when you assign an element to an array that is not compatible with type of data that can
be store in that array

ClassCastException Occurs when you assign a reference variable of a class to an incompatible reference variable of
another class
IllegalArgumentException Occurs when you pass an argument of incompatible data type to a method

NegativeArraySizeException Occurs when you create an array with a negative size

NullPointerException Occurs when an application tries to use an object without allocating memory to it or calls a
method of a null object

NumberFormatException Occurs when you want to convert a String in an incorrect format to a numeric format
Error
• Error is irrecoverable
• e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Checked Exceptions vs. Unchecked Exceptions

• RuntimeException, Error and their subclasses are known as


unchecked exceptions.
• All other exceptions are known as checked exceptions - the
compiler forces the programmer to check and deal with the
exceptions.
Java Exception Keywords
Sample Exceptions
ArithmeticException
• int a=50/0;//ArithmeticException
NullPointerException
• String s=null;
• [Link]([Link]());//NullPointerException
NumberFormatException
• String s="abc";
• int i=[Link](s);//NumberFormatException
ArrayIndexOutOfBoundsException
• int a[]=new int[5];
• a[10]=50; //ArrayIndexOutOfBoundsException
Try Block
• The try block contains a block of program statements within
which an exception might occur
• If an exception occurs at the particular statement of try block,
the rest of the block code will not execute. So, it is
recommended not to keeping the code in try block that will not
throw an exception.
• Java try block must be followed by either catch or finally block.
Syntax
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Try Block
Syntax of try-finally block
try{
//code that may throw an exception
}finally{
}
Catch Block
• The catch block must be used after the try block only.
• You can use multiple catch block with a single try
block.

Syntax
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Sample program
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
[Link]("rest of the code");
}
}
Output
Exception in thread "main"
[Link]: / by zero
Sample Program
public class sample{
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]("rest of the code...");
}
}
Output
Exception in thread main
[Link]:/ by zero
rest of the code...
Nested try block
• The try block within a try block is known as nested try
block in java.
• Sometimes a situation may arise where a part of a
block may cause one error and the entire block itself
may cause another error. In such cases, exception
handlers have to be nested.
Syntax
try
{ statement 1;
statement 2;
try {
statement 1;
statement 2;
}catch(Exception e){
}
}
catch(Exception e)
{
}
....
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
finally block
• Java finally block is a block that is used to execute
important code such as closing connection, stream etc.
• Java finally block is always executed whether
exception is handled or not.
• Java finally block follows try or catch block.
Throw
• 1. Java throw keyword is used to explicitly throw an
exception.
2. Checked exception cannot be propagated using
throw only.
3. Throw is followed by an instance.
4. Throw is used within the method.
5. You cannot throw multiple exceptions.
Throws
1. throws keyword is used to declare an exception.
2. Checked exception can be propagated with throws.
3. Throws is followed by class.
4. Throws is used with the method signature.
5. You can declare multiple exceptions e.g.
6. public void method( )throws
IOException,SQLException.
Syntax
return_type method_name() throws exception_class_na
me{
//method code
}
Sample Program
• public class ExceptionDemo {
public static void main(String[ ] args) throws IOException {
int a = 50;
int b = 0;
try {
if (b == 0) {
throw new ArithmeticException("number cannot be
divided by zero");
} else {
[Link](a / b);
}
} catch (Exception e) {
[Link]( );
}
}
}
Output
• [Link]: number cannot
be divided by zero
Difference between Throw & Throws

No. throw throws

1) Java throw keyword is used to Java throws keyword is used to


explicitly throw an exception. declare an exception.

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions
e.g.
public void method()throws
IOException,SQLException.
Declaring Exceptions: Custom Exception

• If you are creating your own Exception that is known as


custom exception or user-defined exception. Java custom
exceptions are used to customize the exception according to
user need.
• By the help of custom exception, you can have your own
exception and message.
• Let's see a simple example of java custom exception.
Throwing Exceptions
• When the program detects an error, the program can create an
instance of an appropriate exception type and throw it. This is
known as throwing an exception. Here is an example,

throw new TheException();

TheException ex = new TheException();


throw ex;
Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Sample
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s); }
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}
Cont..
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){[Link]("Exception occured:
"+m);}
[Link]("rest of the code...");
}
}
Output
Exception occured: InvalidAgeException:not valid
rest of the code...
Throws
• The Java throws keyword is used to declare an
exception.
• It gives an information to the programmer that there
may occur an exception so it is better for the
programmer to provide the exception handling code so
that normal flow can be maintained.
• Exception Handling is mainly used to handle the
checked exceptions.
• If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he
is not performing check up before the code being used.
Syntax
return_type method_name() throws exception_class_na
me{
//method code
}
Sample Program
import [Link].*;
class M{
void method()throws IOException{
[Link]("device operation performed");
} }
class Testthrows3{
public static void main(String args[])throws IOException{//declare e
xception
M m=new M();
[Link]();
[Link]("normal flow...");
}}
Output
device operation performed
normal flow...
Difference between Throw & Throws

No. throw throws

1) Java throw keyword is used to Java throws keyword is used to


explicitly throw an exception. declare an exception.

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions
e.g.
public void method()throws
IOException,SQLException.
Thread
• A thread is a lightweight sub-process, the smallest unit
of processing.
• Multiprocessing and multithreading, both are used to
achieve multitasking.

There are two ways to create a thread:


• By extending Thread class
• By implementing Runnable interface.
Advantages
• It doesn't block the user because threads are
independent and you can perform multiple operations
at same time.
• You can perform many operations together so it
saves time.
• Threads are independent so it doesn't affect other
threads if exception occur in a single thread.
Life Cycle of Thread
Sample Program
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
Output
thread is running...
Runnable Interface
• public class Sample implements Runnable {
public void run( ) {
[Link]("Thread is invoked" );
}

public static void main(String args[ ]) {


Sample t1 = new Sample( );
Thread obj=new Thread(t1);
[Link]( );
}
}
Output
• Thread is invoked
Thread Synchronization
• Synchronization in java is the capability to control the
access of multiple threads to any shared resource.
• Java Synchronization is better option where we want
to allow only one thread to access the shared resource

Types of Synchronization
• There are two types of synchronization
• Process Synchronization
• Thread Synchronization
Why use Synchronization
The synchronization is mainly used to
• To prevent thread interference.
• To prevent consistency problem.
Thread Synchronization
• There are two types of thread synchronization mutual
exclusive and inter-thread communication.
• Mutual Exclusive
• Synchronized method.
• Synchronized block.
• static synchronization.
• Cooperation (Inter-thread communication in java)
Mutual Exclusive
• Mutual Exclusive helps keep threads from interfering
with one another while sharing data.

• This can be done by three ways in java:


1. by synchronized method
2. by synchronized block
3. by static synchronization
Concept of Lock in Java
• Synchronization is built around an internal entity
known as the lock or monitor. Every object has an
lock associated with it. By convention, a thread that
needs consistent access to an object's fields has to
acquire the object's lock before accessing them, and
then release the lock when it's done with them.
• From Java 5 the package [Link]
contains several lock implementations.
Understanding the problem without Synchronization
class Table{
void printTable(int n){
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);} } } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
} public void run(){
[Link](5); } }
Conti…
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t; } public void run(){
[Link](100); } }
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link](); } }
Output
5
100
10
200
15
300
20
400
25
500
Java synchronized method
• If you declare any method as synchronized, it is
known as synchronized method.
• Synchronized method is used to lock an object for any
shared resource.
• When a thread invokes a synchronized method, it
automatically acquires the lock for that object and
releases it when the thread completes its task.
Sample Program
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);} } } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
} public void run(){
[Link](5); } }
Conti…
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t; } public void run(){
[Link](100); } }
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link](); } }
Output
5
10
15
20
25
100
200
300
400
50
Synchronized Block in Java
• Synchronized block can be used to perform
synchronization on any specific resource of the
method.
• Suppose you have 50 lines of code in your method,
but you want to synchronize only 5 lines, you can use
synchronized block.
• If you put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
• Synchronized block is used to lock an object for any
shared resource.
• Scope of synchronized block is smaller than the
method.
Syntax to use synchronized block
synchronized (object reference expression) {
//code block
}
Sample Program
class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);} } } } //end of the method
}class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
} public void run(){
[Link](5); } }
Conti…
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t; } public void run(){
[Link](100); } }
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link](); } }
Output
5
10
15
20
25
100
200
300
400
50
Static Synchronization
• If you make any static method as synchronized, the
lock will be on the class not on object.
• synchronized keyword on the static method to perform
static synchronization.
Cont..
• Suppose there are two objects of a shared class(e.g.
Table) named object1 and object2.
• In case of synchronized method and synchronized
block there cannot be interference between t1 and t2
or t3 and t4 because t1 and t2 both refers to a common
object that have a single lock.
• But there can be interference between t1 and t3 or t2
and t4 because t1 acquires another lock and t3
acquires another lock.
• I want no interference between t1 and t3 or t2 and
[Link] synchronization solves this problem.
Sample Program
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
} } //end of the method
}class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
} public void run(){
[Link](5); } }
Conti…
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t; } public void run(){
[Link](100); } }
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link](); } }

You might also like