SlideShare a Scribd company logo
Introduction to Java Programming Language
Unit-11 [Exception Handling]
The exception handling in java is used to handle the runtime errors so that normal flow of the
application can be maintained. A Java Exception is an object that describes the exception that occurs
in a program. When an exceptional events occurs in java, an exception is said to be thrown. The
code that's responsible for doing something about the exception is called an exception handler.
Exception Class Hierarchy
All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.
Below is a brief description of all classes mentioned here:
• Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
• RuntimeException is a subclass of Exception. Exceptions under this class are automatically
defined for programs.
• Exceptions of type Error are used by the Java run-time system to indicate errors having to
do with the run-time environment, itself. Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, Stack OverflowError.
Types of Exception:
1. Checked exceptions: Checked exceptions are checked at compile-time. Note that, the classes
that extend Throwable class except RuntimeException and Error are known as checked exceptions.
e.g.IOException, SQLException etc.
2. Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3. Errors: These are typically ignored in code because you can rarely do anything about an error.
Example :if stack overflow occurs, an error will arise. This type of error cannot be handled in the
code.
Provided By Shipra Swati
Introduction to Java Programming Language
Examples:
1) ArithmeticException occurs: If we divide any number by zero, there occurs an
ArithmeticException.
Int a=50/0; //ArithmeticException
2) Scenario where NullPointerException occurs: If we have null value in any variable,
performing any operation by the variable occurs an NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
3) Scenario where NumberFormatException occurs: The wrong formatting of any value, may
occur NumberFormatException. Suppose I have a string variable that have characters, converting
this variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs: If you are inserting any value in
the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
Int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
There are 5 keywords used in java exception handling:
1. try
2. catch
3. finally
4. throw
5. throws
Java Program of Exception Example:
class Excp{
 public static void main(String args[]) {
  int a,b,c;
  try {
   a=0;
   b=10;
   c=b/a;
   System.out.println("This line will not be executed");
  }
  catch(ArithmeticException e)  {
   System.out.println("Divided by zero"); 
  }
  System.out.println("After exception is handled");
 }
}
Output
Divided by zero
After exception is handled
Provided By Shipra Swati
Introduction to Java Programming Language
Try is used to guard a block of code in which exception may occur. This block of code is called
guarded region. A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in guarded code, the catch block that follows the try is checked, if the type of
exception that occured is listed in the catch block then the exception is handed over to the catch
block which then handles it.
An exception will be thrown by this program as we are trying to divide a number by zero inside try
block. The program control is transferred outside try block. Thus the line "This line will not be
executed" is never parsed by the compiler. The exception thrown is handled in catch block. Once
the exception is handled, the program control is continue with the next line in the program i.e after
catch block. Thus the line "After exception is handled" is printed.
Exceptions throws and throw clause
throw clause
throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub
classes can be thrown. Program execution stops on encountering throw statement, and the closest
catch statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance
Provided By Shipra Swati
Introduction to Java Programming Language
Example:
class Test{
 static void avg()  {
  try
  {
   throw new ArithmeticException("demo");
  }
  catch(ArithmeticException e)  {
   System.out.println("Exception caught");
  } 
 }
 public static void main(String args[]) {
  avg(); 
 }
}
new   ArithmeticException("demo")  constructs an instance of ArithmeticException with
name “demo”. The avg() method throw an instance of ArithmeticException, which is successfully
handled using the catch statement and thus, the program outputs:
"Exception caught"
throws clause
Any method that is capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions are to
be handled. A method can do so by using the throws keyword.
General syntax of throws:
type method_name(parameter_list) throws exception_list
{
 //definition of method
}
Example:
class Test{
 static void check() throws ArithmeticException {
  System.out.println("Inside check function");
  throw new ArithmeticException("demo");
 }
 public static void main(String args[]) {
  try  {
   check();
  }
  catch(ArithmeticException e)  {
   System.out.println("caught" + e);
  }
 }
}
Provided By Shipra Swati
Introduction to Java Programming Language
Output
Inside check function
caughtjava.lang.ArithmeticException: demo
Difference between throw and throws
throw throws
throw keyword is used to throw an exception
explicitly.
throws keyword is used to declare an exception
possible during its execution.
throw keyword is followed by an instance of
Throwable class or one of its sub-classes.
throws keyword is followed by one or more
Exception class names separated by commas.
throw keyword is declared inside a method
body.
throws keyword is used with method signature
(method declaration).
We cannot throw multiple exceptions using
throw keyword.
We can declare multiple exceptions (separated by
commas) using throws keyword.
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code
is always executed whether an exception has occurred or not. Using a finally block, it lets you run
any cleanup type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of catch block.
In the following example, you can see in above example even if exception is thrown by the
program, which is not handled by catch block, still finally block will get executed.
Example
Class ExceptionTest{
 public static void main(String[] args) {
  int a[]= new int[2];
  System.out.println("out of try");
  try   {
   System.out.println("Access invalid element"+ a[3]);
   /* the above statement will throw ArrayIndexOutOfBoundException */
  }
  finally   {
   System.out.println("finally is always executed.");
  }
 }
}
Output
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.
Provided By Shipra Swati
Introduction to Java Programming Language
Related University Question
1. Discuss java error handling mechanism. What is the difference between runtime (unchecked)
exceptions and checked exceptions? what is the implication of catching all the exceptions with the
type 'exception'?
[Year 2015]
2. What is exception handling? What are the statements used for it? Show an example. [Year 2016]
Provided By Shipra Swati

More Related Content

What's hot (20)

PPT
Exception handling
Raja Sekhar
 
PPTX
Java exception handling
Md. Tanvir Hossain
 
PPTX
Exception handling in java
yugandhar vadlamudi
 
PPT
Chap12
Terry Yoast
 
PPT
exception handling in java
aptechsravan
 
PDF
Best Practices in Exception Handling
Lemi Orhan Ergin
 
PPTX
7.error management and exception handling
Deepak Sharma
 
PPTX
Chap2 exception handling
raksharao
 
PPT
9781439035665 ppt ch11
Terry Yoast
 
ODP
Exception Handling In Java 15734
madhurendra pandey
 
PPT
Exception handling in java
Pratik Soares
 
PPTX
Exception handling in JAVA
Kunal Singh
 
PPTX
Exception handling in java
ravinderkaur165
 
PPTX
Exception handling
Abhishek Pachisia
 
PPT
Exceptions
DeepikaT13
 
PPTX
Exception handling in java
pooja kumari
 
PPT
exception handling
Manav Dharman
 
PPTX
Exceptionhandling
Nuha Noor
 
PPT
Types of exceptions
myrajendra
 
PPTX
Exception handling
PhD Research Scholar
 
Exception handling
Raja Sekhar
 
Java exception handling
Md. Tanvir Hossain
 
Exception handling in java
yugandhar vadlamudi
 
Chap12
Terry Yoast
 
exception handling in java
aptechsravan
 
Best Practices in Exception Handling
Lemi Orhan Ergin
 
7.error management and exception handling
Deepak Sharma
 
Chap2 exception handling
raksharao
 
9781439035665 ppt ch11
Terry Yoast
 
Exception Handling In Java 15734
madhurendra pandey
 
Exception handling in java
Pratik Soares
 
Exception handling in JAVA
Kunal Singh
 
Exception handling in java
ravinderkaur165
 
Exception handling
Abhishek Pachisia
 
Exceptions
DeepikaT13
 
Exception handling in java
pooja kumari
 
exception handling
Manav Dharman
 
Exceptionhandling
Nuha Noor
 
Types of exceptions
myrajendra
 
Exception handling
PhD Research Scholar
 

Similar to Java unit 11 (20)

PPTX
Interface andexceptions
saman Iftikhar
 
PPTX
Exception handling in java.pptx
Nagaraju Pamarthi
 
PDF
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
PPTX
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
PDF
Exception handling
Garuda Trainings
 
PDF
Exception handling
Garuda Trainings
 
PPTX
Exception handling in java
pooja kumari
 
PPTX
Java-Unit 3- Chap2 exception handling
raksharao
 
PPTX
Exception Handling.pptx
primevideos176
 
PPT
Java exception
Arati Gadgil
 
PPTX
Exception handling
Ardhendu Nandi
 
PDF
Exception handling basic
TharuniDiddekunta
 
PPTX
Exception handling in java
ARAFAT ISLAM
 
PPT
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
PPTX
L14 exception handling
teach4uin
 
PPTX
Exception handling in java
Elizabeth alexander
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPTX
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
PPTX
Exception Hnadling java programming language
ushakiranv110
 
PPTX
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Interface andexceptions
saman Iftikhar
 
Exception handling in java.pptx
Nagaraju Pamarthi
 
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Exception handling
Garuda Trainings
 
Exception handling
Garuda Trainings
 
Exception handling in java
pooja kumari
 
Java-Unit 3- Chap2 exception handling
raksharao
 
Exception Handling.pptx
primevideos176
 
Java exception
Arati Gadgil
 
Exception handling
Ardhendu Nandi
 
Exception handling basic
TharuniDiddekunta
 
Exception handling in java
ARAFAT ISLAM
 
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
L14 exception handling
teach4uin
 
Exception handling in java
Elizabeth alexander
 
Exception Handling in JAVA
SURIT DATTA
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Exception Hnadling java programming language
ushakiranv110
 
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Ad

More from Shipra Swati (20)

PDF
Operating System-Process Scheduling
Shipra Swati
 
PDF
Operating System-Concepts of Process
Shipra Swati
 
PDF
Operating System-Introduction
Shipra Swati
 
PDF
Java unit 14
Shipra Swati
 
PDF
Java unit 12
Shipra Swati
 
PDF
Java unit 7
Shipra Swati
 
PDF
Java unit 3
Shipra Swati
 
PDF
Java unit 2
Shipra Swati
 
PDF
Java unit 1
Shipra Swati
 
PDF
OOPS_Unit_1
Shipra Swati
 
PDF
Ai lab manual
Shipra Swati
 
PDF
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
PDF
Fundamental of Information Technology - UNIT 7
Shipra Swati
 
PDF
Fundamental of Information Technology - UNIT 6
Shipra Swati
 
PDF
Fundamental of Information Technology
Shipra Swati
 
PDF
Disk Management
Shipra Swati
 
PDF
File Systems
Shipra Swati
 
PDF
Memory Management
Shipra Swati
 
PDF
Deadlocks
Shipra Swati
 
PDF
Process Synchronization
Shipra Swati
 
Operating System-Process Scheduling
Shipra Swati
 
Operating System-Concepts of Process
Shipra Swati
 
Operating System-Introduction
Shipra Swati
 
Java unit 14
Shipra Swati
 
Java unit 12
Shipra Swati
 
Java unit 7
Shipra Swati
 
Java unit 3
Shipra Swati
 
Java unit 2
Shipra Swati
 
Java unit 1
Shipra Swati
 
OOPS_Unit_1
Shipra Swati
 
Ai lab manual
Shipra Swati
 
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
Fundamental of Information Technology - UNIT 7
Shipra Swati
 
Fundamental of Information Technology - UNIT 6
Shipra Swati
 
Fundamental of Information Technology
Shipra Swati
 
Disk Management
Shipra Swati
 
File Systems
Shipra Swati
 
Memory Management
Shipra Swati
 
Deadlocks
Shipra Swati
 
Process Synchronization
Shipra Swati
 
Ad

Recently uploaded (20)

PPTX
Data_Analytics_Presentation_By_Malik_Azanish_Asghar.pptx
azanishmalik1
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PDF
13th International Conference of Networks and Communications (NC 2025)
JohannesPaulides
 
PDF
PRIZ Academy - Change Flow Thinking Master Change with Confidence.pdf
PRIZ Guru
 
PDF
SMART HOME AUTOMATION PPT BY - SHRESTH SUDHIR KOKNE
SHRESTHKOKNE
 
PDF
BioSensors glucose monitoring, cholestrol
nabeehasahar1
 
PPTX
Mining Presentation Underground - Copy.pptx
patallenmoore
 
PPTX
File Strucutres and Access in Data Structures
mwaslam2303
 
PDF
Comparative Analysis of the Use of Iron Ore Concentrate with Different Binder...
msejjournal
 
PDF
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
PDF
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
PPTX
Unit II: Meteorology of Air Pollution and Control Engineering:
sundharamm
 
PDF
IoT - Unit 2 (Internet of Things-Concepts) - PPT.pdf
dipakraut82
 
PPTX
purpose of this tutorial is to introduce you to Computers and its fundamentals.
rameshwardayalrao1
 
PDF
1_ISO Certifications by Indian Industrial Standards Organisation.pdf
muhammad2010960
 
PPTX
Coding about python and MySQL connectivity
inderjitsingh1985as
 
PDF
POWER PLANT ENGINEERING (R17A0326).pdf..
haneefachosa123
 
PPTX
Electron Beam Machining for Production Process
Rajshahi University of Engineering & Technology(RUET), Bangladesh
 
PPTX
Cyclic_Redundancy_Check_Presentation.pptx
alhjranyblalhmwdbdal
 
PPT
Oxygen Co2 Transport in the Lungs(Exchange og gases)
SUNDERLINSHIBUD
 
Data_Analytics_Presentation_By_Malik_Azanish_Asghar.pptx
azanishmalik1
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
13th International Conference of Networks and Communications (NC 2025)
JohannesPaulides
 
PRIZ Academy - Change Flow Thinking Master Change with Confidence.pdf
PRIZ Guru
 
SMART HOME AUTOMATION PPT BY - SHRESTH SUDHIR KOKNE
SHRESTHKOKNE
 
BioSensors glucose monitoring, cholestrol
nabeehasahar1
 
Mining Presentation Underground - Copy.pptx
patallenmoore
 
File Strucutres and Access in Data Structures
mwaslam2303
 
Comparative Analysis of the Use of Iron Ore Concentrate with Different Binder...
msejjournal
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
Unit II: Meteorology of Air Pollution and Control Engineering:
sundharamm
 
IoT - Unit 2 (Internet of Things-Concepts) - PPT.pdf
dipakraut82
 
purpose of this tutorial is to introduce you to Computers and its fundamentals.
rameshwardayalrao1
 
1_ISO Certifications by Indian Industrial Standards Organisation.pdf
muhammad2010960
 
Coding about python and MySQL connectivity
inderjitsingh1985as
 
POWER PLANT ENGINEERING (R17A0326).pdf..
haneefachosa123
 
Electron Beam Machining for Production Process
Rajshahi University of Engineering & Technology(RUET), Bangladesh
 
Cyclic_Redundancy_Check_Presentation.pptx
alhjranyblalhmwdbdal
 
Oxygen Co2 Transport in the Lungs(Exchange og gases)
SUNDERLINSHIBUD
 

Java unit 11

  • 1. Introduction to Java Programming Language Unit-11 [Exception Handling] The exception handling in java is used to handle the runtime errors so that normal flow of the application can be maintained. A Java Exception is an object that describes the exception that occurs in a program. When an exceptional events occurs in java, an exception is said to be thrown. The code that's responsible for doing something about the exception is called an exception handler. Exception Class Hierarchy All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy. Below is a brief description of all classes mentioned here: • Exception class is for exceptional conditions that program should catch. This class is extended to create user specific exception classes. • RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for programs. • Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, Stack OverflowError. Types of Exception: 1. Checked exceptions: Checked exceptions are checked at compile-time. Note that, the classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. e.g.IOException, SQLException etc. 2. Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. 3. Errors: These are typically ignored in code because you can rarely do anything about an error. Example :if stack overflow occurs, an error will arise. This type of error cannot be handled in the code. Provided By Shipra Swati
  • 2. Introduction to Java Programming Language Examples: 1) ArithmeticException occurs: If we divide any number by zero, there occurs an ArithmeticException. Int a=50/0; //ArithmeticException 2) Scenario where NullPointerException occurs: If we have null value in any variable, performing any operation by the variable occurs an NullPointerException. String s=null; System.out.println(s.length()); //NullPointerException 3) Scenario where NumberFormatException occurs: The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException. String s="abc"; int i=Integer.parseInt(s); //NumberFormatException 4) Scenario where ArrayIndexOutOfBoundsException occurs: If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below: Int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException There are 5 keywords used in java exception handling: 1. try 2. catch 3. finally 4. throw 5. throws Java Program of Exception Example: class Excp{  public static void main(String args[]) {   int a,b,c;   try {    a=0;    b=10;    c=b/a;    System.out.println("This line will not be executed");   }   catch(ArithmeticException e)  {    System.out.println("Divided by zero");    }   System.out.println("After exception is handled");  } } Output Divided by zero After exception is handled Provided By Shipra Swati
  • 3. Introduction to Java Programming Language Try is used to guard a block of code in which exception may occur. This block of code is called guarded region. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in guarded code, the catch block that follows the try is checked, if the type of exception that occured is listed in the catch block then the exception is handed over to the catch block which then handles it. An exception will be thrown by this program as we are trying to divide a number by zero inside try block. The program control is transferred outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handled in catch block. Once the exception is handled, the program control is continue with the next line in the program i.e after catch block. Thus the line "After exception is handled" is printed. Exceptions throws and throw clause throw clause throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. Syntax : throw ThrowableInstance Provided By Shipra Swati
  • 4. Introduction to Java Programming Language Example: class Test{  static void avg()  {   try   {    throw new ArithmeticException("demo");   }   catch(ArithmeticException e)  {    System.out.println("Exception caught");   }   }  public static void main(String args[]) {   avg();   } } new   ArithmeticException("demo")  constructs an instance of ArithmeticException with name “demo”. The avg() method throw an instance of ArithmeticException, which is successfully handled using the catch statement and thus, the program outputs: "Exception caught" throws clause Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword. General syntax of throws: type method_name(parameter_list) throws exception_list {  //definition of method } Example: class Test{  static void check() throws ArithmeticException {   System.out.println("Inside check function");   throw new ArithmeticException("demo");  }  public static void main(String args[]) {   try  {    check();   }   catch(ArithmeticException e)  {    System.out.println("caught" + e);   }  } } Provided By Shipra Swati
  • 5. Introduction to Java Programming Language Output Inside check function caughtjava.lang.ArithmeticException: demo Difference between throw and throws throw throws throw keyword is used to throw an exception explicitly. throws keyword is used to declare an exception possible during its execution. throw keyword is followed by an instance of Throwable class or one of its sub-classes. throws keyword is followed by one or more Exception class names separated by commas. throw keyword is declared inside a method body. throws keyword is used with method signature (method declaration). We cannot throw multiple exceptions using throw keyword. We can declare multiple exceptions (separated by commas) using throws keyword. finally clause A finally keyword is used to create a block of code that follows a try block. A finally block of code is always executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block. In the following example, you can see in above example even if exception is thrown by the program, which is not handled by catch block, still finally block will get executed. Example Class ExceptionTest{  public static void main(String[] args) {   int a[]= new int[2];   System.out.println("out of try");   try   {    System.out.println("Access invalid element"+ a[3]);    /* the above statement will throw ArrayIndexOutOfBoundException */   }   finally   {    System.out.println("finally is always executed.");   }  } } Output Out of try finally is always executed. Exception in thread main java. Lang. exception array Index out of bound exception. Provided By Shipra Swati
  • 6. Introduction to Java Programming Language Related University Question 1. Discuss java error handling mechanism. What is the difference between runtime (unchecked) exceptions and checked exceptions? what is the implication of catching all the exceptions with the type 'exception'? [Year 2015] 2. What is exception handling? What are the statements used for it? Show an example. [Year 2016] Provided By Shipra Swati