SlideShare a Scribd company logo
Exception HandlingException Handling
By
Nilesh Dalvi
Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College.
http://www.slideshare.net/nileshdalvi01
Java and Data StructuresJava and Data Structures
Introduction
• An exception is a condition that is caused by a run-time error in
the program.
– Example: Dividing integer by zero. ( / by zero)
• Java has special mechanism for handling such types of errors.
• Its Exception handling.
• Core advantage of exception handling is to maintain the normal
flow of the application.
• Mechanism performs following tasks:
– Find the problem (Hit the exception)
– Inform that error has occur(Throw the exception)
– Receive the error information(catch the exception)
– Take a correct action (Handle the exception)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Exceptions
Categorized into two types:
• Checked exception:
– Explicitly handle in the code itself with the help of try-catch block.
– Extended from java.lang.Exception class
– e.g.IOException, SQLException etc.
• Unchecked exception:
– Not handle in the program code .
– JVM handles such exceptions.
– Extended from the java.lang.RuntimeException
– e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Common Java Exceptions
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Exception Description
ClassNotFoundException Class not found.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Exception Description
Common Java Exceptions
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException
Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NullPointerException Invalid use of a null reference.
NumberFormatException
Invalid conversion of a string to a
numeric format.
StringIndexOutOfBounds
Attempt to index outside the bounds of
a string.
try and catch block
• Enclose the code that might throw an exception in try block.
• It must be used within the method and must be followed by
either catch or finally block.
• Syntax of try with catch block
• Syntax of try with finally block
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
try{  
...  
}catch(Exception_class_Name reference)
{}  
try{  
...  
}finally
{}  
try and catch block
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class Testtrycatch
{
public static void main(String args[])
{
int data = 50/0;
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
try and catch block
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class Testtrycatch
{
public static void main(String args[])
{
try{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Multiple Catch blocks
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class MultipleCatch
{
public static void main(String argv[])
{
int num1 = 10;
int num2 = 0;
int result = 0;
int arr[] = new int[5];
try
{
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
arr[4] = 4;
arr[5] = 5;
result = num1 / num2;
System.out.println("Result of Division : " + result);
}catch (ArithmeticException e) {
System.out.println("Err: Divided by Zero");
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Err: Array Out of Bound");
}
}
}
Nested try…block
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class NestedTryBlock
{
public static void main(String args[])
{
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){
System.out.println(e);
}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
finally
• The finally block is a block that is always executed.
• It is mainly used to perform some important tasks such
as closing connection, stream etc.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
finally
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class FinallyBlock
{
public static void main(String args[])
{
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally{
System.out.println("finally block is
always executed");
}
System.out.println("rest of the code...");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
throw
• The throw keyword is used to explicitly throw an
exception.
• We can throw either checked or uncheked exception.
• The throw keyword is mainly used to throw custom
exception.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
throws
throws clause is used to handle the exception thrown by methods
in program.
void method_name() throws exception_class_name
{  
 ...   
}  
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Q & A

More Related Content

What's hot

6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructorsRavi_Kant_Sahu
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
Lovely Professional University
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variablesRavi_Kant_Sahu
 

What's hot (8)

Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Array
ArrayArray
Array
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
Java keywords
Java keywordsJava keywords
Java keywords
 

Viewers also liked

Exception handling
Exception handlingException handling
Exception handling
Anna Pietras
 
14. Linked List
14. Linked List14. Linked List
14. Linked List
Nilesh Dalvi
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
Nilesh Dalvi
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
Nilesh Dalvi
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
Nilesh Dalvi
 
13. Queue
13. Queue13. Queue
13. Queue
Nilesh Dalvi
 
12. Stack
12. Stack12. Stack
12. Stack
Nilesh Dalvi
 

Viewers also liked (7)

Exception handling
Exception handlingException handling
Exception handling
 
14. Linked List
14. Linked List14. Linked List
14. Linked List
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
 
13. Queue
13. Queue13. Queue
13. Queue
 
12. Stack
12. Stack12. Stack
12. Stack
 

Similar to 6. Exception Handling

JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
Jyothishmathi Institute of Technology and Science Karimnagar
 
Exception handling2.0.pptx
Exception handling2.0.pptxException handling2.0.pptx
Exception handling2.0.pptx
SelvakumarNSNS
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
Pramod Yadav
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
Waheed Warraich
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questions
Mehtaacademy
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
FacultyAnupamaAlagan
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
SivaSankari36
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
Nalinee Choudhary
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
PawanMM
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
chauhankapil
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
JasmeetSingh326
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
sonukumarjha12
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
KALAISELVI P
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 

Similar to 6. Exception Handling (20)

JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
Exception handling2.0.pptx
Exception handling2.0.pptxException handling2.0.pptx
Exception handling2.0.pptx
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
 
Exceptions
ExceptionsExceptions
Exceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questions
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 

More from Nilesh Dalvi

Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
Nilesh Dalvi
 
Templates
TemplatesTemplates
Templates
Nilesh Dalvi
 
File handling
File handlingFile handling
File handling
Nilesh Dalvi
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
Strings
StringsStrings
Strings
Nilesh Dalvi
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Nilesh Dalvi
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Nilesh Dalvi
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Nilesh Dalvi
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
Nilesh Dalvi
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 

More from Nilesh Dalvi (12)

Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Templates
TemplatesTemplates
Templates
 
File handling
File handlingFile handling
File handling
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Strings
StringsStrings
Strings
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 

6. Exception Handling

  • 1. Exception HandlingException Handling By Nilesh Dalvi Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College. http://www.slideshare.net/nileshdalvi01 Java and Data StructuresJava and Data Structures
  • 2. Introduction • An exception is a condition that is caused by a run-time error in the program. – Example: Dividing integer by zero. ( / by zero) • Java has special mechanism for handling such types of errors. • Its Exception handling. • Core advantage of exception handling is to maintain the normal flow of the application. • Mechanism performs following tasks: – Find the problem (Hit the exception) – Inform that error has occur(Throw the exception) – Receive the error information(catch the exception) – Take a correct action (Handle the exception) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 3. Exceptions Categorized into two types: • Checked exception: – Explicitly handle in the code itself with the help of try-catch block. – Extended from java.lang.Exception class – e.g.IOException, SQLException etc. • Unchecked exception: – Not handle in the program code . – JVM handles such exceptions. – Extended from the java.lang.RuntimeException – e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 4. Common Java Exceptions Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Exception Description ClassNotFoundException Class not found. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist. Exception Description
  • 5. Common Java Exceptions Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Exception Description ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid cast. IndexOutOfBoundsException Some type of index is out-of-bounds. NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. StringIndexOutOfBounds Attempt to index outside the bounds of a string.
  • 6. try and catch block • Enclose the code that might throw an exception in try block. • It must be used within the method and must be followed by either catch or finally block. • Syntax of try with catch block • Syntax of try with finally block Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). try{   ...   }catch(Exception_class_Name reference) {}   try{   ...   }finally {}  
  • 7. try and catch block Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class Testtrycatch { public static void main(String args[]) { int data = 50/0; System.out.println("rest of the code..."); } } Output:Exception in thread main java.lang.ArithmeticException:/ by zero
  • 8. try and catch block Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class Testtrycatch { public static void main(String args[]) { try{ int data=50/0; } catch(ArithmeticException e) { System.out.println(e); } System.out.println("rest of the code..."); } } Output:Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...
  • 9. Multiple Catch blocks Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class MultipleCatch { public static void main(String argv[]) { int num1 = 10; int num2 = 0; int result = 0; int arr[] = new int[5]; try { arr[0] = 0; arr[1] = 1; arr[2] = 2; arr[3] = 3; arr[4] = 4; arr[5] = 5; result = num1 / num2; System.out.println("Result of Division : " + result); }catch (ArithmeticException e) { System.out.println("Err: Divided by Zero"); }catch (ArrayIndexOutOfBoundsException e) { System.out.println("Err: Array Out of Bound"); } } }
  • 10. Nested try…block Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class NestedTryBlock { public static void main(String args[]) { try{ try{ System.out.println("going to divide"); int b =39/0; }catch(ArithmeticException e){ System.out.println(e); } try{ int a[]=new int[5]; a[5]=4; }catch(ArrayIndexOutOfBoundsException e) { System.out.println(e);} System.out.println("other statement); }catch(Exception e){System.out.println("handeled");} System.out.println("normal flow.."); } }
  • 11. finally • The finally block is a block that is always executed. • It is mainly used to perform some important tasks such as closing connection, stream etc. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 12. finally Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class FinallyBlock { public static void main(String args[]) { try{ int data=25/0; System.out.println(data); } catch(ArithmeticException e){ System.out.println(e); } finally{ System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } Output: Exception in thread main java.lang.ArithmeticException:/ by zero finally block is always executed rest of the code...
  • 13. throw • The throw keyword is used to explicitly throw an exception. • We can throw either checked or uncheked exception. • The throw keyword is mainly used to throw custom exception. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 14. throws throws clause is used to handle the exception thrown by methods in program. void method_name() throws exception_class_name {    ...    }   Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 15. Q & A