SlideShare a Scribd company logo
1 of 28
www.SunilOS.com 1
Exception Handling
throw
catch
www.sunilos.com
www.raystec.com
www.SunilOS.com 2
Exception
Exceptional (that is error) condition that has
occurred in a piece of code of Java program.
www.SunilOS.com 3
Exception
 It will cause abnormal termination of program or wrong
execution result.
 Java provides an exception handling mechanism to handle
exceptions.
 Exception handling will improve the reliability of application
program.
 Java creates different type of objects in case of different
exceptional conditions that describe the cause of exception.
www.SunilOS.com 4
Exception Definition
Treat exception as an object.
All exceptions are instances of a class extended
from Throwable class or its subclass.
Generally, a programmer can make new
exception class by extending the Exception
class which is subclass of Throwable class.
www.SunilOS.com 5
Hierarchical Structure of Throwable Class
ObjectObject
ThrowableThrowable
ErrorError ExceptionException
RuntimeExceptionRuntimeException
...
...
...
www.SunilOS.com 6
Exception Types
Error Class
o Abnormal conditions those
can NOT be handled are
called Errors.
Exception Class
o Abnormal conditions those
can be handled are called
Exceptions.
Java Exception class hierarchy
www.SunilOS.com 7
ObjectObject
Error
ThrowableThrowable
ExceptionException
LinkageError
VirtualMachoneError
ClassNotFoundExceptionClassNotFoundException
FileNotFoundExceptionFileNotFoundException
IOExceptionIOException
AWTError
…
AWTExceptionAWTException
RuntimeException
…
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Unchecked
CheckedChecked
NoSuchElementException
…
: try-catch block is mandatory
: try-catch block is optional
www.SunilOS.com 8
Exception Handling
 Exception handling is managed by five keywords try, catch, throw,
throws, and finally.
 Exceptions can be generated by
o Java “run-time system” are called System-generated exceptions. It
is automatically raised by Java run-time system.
o Your code are called Programmatic Exceptions. It is raised by
throw keyword.
 When an exceptional condition arises, an object is created that contains
exception description.
 Handling is done with help of try-catch-finally block.
 Exception raised in try block is caught by catch block.
 Block finally is optional and always executed.
www.SunilOS.com 9
try-catch-finally Statement
 try {
 // code
 } catch (ExceptionType1 identifier) {
 // alternate flow 1
 } catch (ExceptionType2 identifier) {
 // alternate flow 2
 } finally {
 //Resource release statements like close file ,
 //close N/W connection,
 //close Database connection, Release memory cache.
 }
Uncaught Exception
 public class TestArithmetic {
 public static void main(String[] args) {
o int k = 0;
o int i = 15;
o double div = i / k;
o System.out.println("Div is " + div);
 }}
www.SunilOS.com 10
Output
java.lang.ArithmeticException: / by zero
at TestArithmetic .main(TestArithmetic .java:5)
JVM detects that number is divided by zero that will produce infinity.
Since infinity can be stored that is why it makes a new exception object
and then throws this exception.
Output
java.lang.ArithmeticException: / by zero
at TestArithmetic .main(TestArithmetic .java:5)
JVM detects that number is divided by zero that will produce infinity.
Since infinity can be stored that is why it makes a new exception object
and then throws this exception.
Stack Trace
Exception Output
www.SunilOS.com 11
Exception class Exception Message
Exception Line Number
 JVM detects the attempt to divide by zero, it makes new
exception object.
 java.lang.ArithmeticException: / by zero
 at TestArithmetic .main( TestArithmetic .java:5)
Handle Exception
 public class TestArithmetic {
 public static void main(String[] args) {
o int k = 0; int i = 15;
o try {
• double div = i / k;
• System.out.println("Div is " + div);
o } catch (ArithmeticException e) {
• System.out.println(“Divided by Zero");
o }
 }}
www.SunilOS.com 12
Output
Divided by Zero
Notice that the call to println( ) inside the try block is never executed
Output
Divided by Zero
Notice that the call to println( ) inside the try block is never executed
Flow of execution
• try {
• a
• b //Throw Exception
• c
• } catch (Exception e) {
• d
• e
• } finally {
• f
• }
Normal Flow
a b c f
Exceptional Flow
 a b d e f
www.SunilOS.com 13
Exception methods
 Object received in catch block contains two key methods
o e.getMessage(); //displays error message.
• / by zero
o e.printStackTrace(); //displays complete trace of exception
• java.lang.ArithmeticException: / by zero
• at TestArithmetic .main( TestArithmetic .java:5)
www.SunilOS.com 14
Multiple catch blocks
 More than one exception could be raised by a single try
block. To handle this type of situation, you can specify two
or more catch blocks.
 String name = “Vijay”;
 try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7th position is " + name.charAt(6));
 } catch (StringIndexOutOfBoundsException e) {
o System.out.println("String abhi choti he!!");
 } catch (NullPointerException e) {
o System.out.println(“Sundar sa nam nahi he!");
 } finally {
o System.out.println(“Pandit hu me");
 }
www.SunilOS.com 15
Multiple catch blocks (cont. )
 More than one exception could be raised by a single try
block. To handle this type of situation, you can specify two
or more catch blocks.
 String name = null;
 try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7th position is " + name.charAt(6));
 } catch (StringIndexOutOfBoundsException e) {
o System.out.println("String abhi choti he!!");
 } catch (NullPointerException e) {
o System.out.println(“Sundar sa nam nahi he!");
 } finally {
o System.out.println(“Pandit hu me");
 }
www.SunilOS.com 16
Parent catch
 String name = “Vijay”;
 try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7 position is " + name.charAt(6));
 } catch (StringIndexOutOfBoundsException e) {
o System.out.println("String abhi choti he!!");
 } catch (RuntimeException e) {
o System.out.println(“Sundar sa nam nahi he!");
 } finally {
o System.out.println(“Pandit hu me");
 }
www.SunilOS.com 17
Generic Catch
 A catch block of Parent Class can handle exceptions of its sub classes.
It can be used as a generic catch to handle multiple exceptions in down
hierarchy.
 String name = “Vijay”;
 try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7th position is " + name.charAt(6));
 } catch (Exception e) {
o System.out.println(“Error ” + e.getMessage() );
 }
www.SunilOS.com 18
Order of catch blocks: Parent & Child
 Catch block of a Child class must come first in the order, if
Parent’s class catch does exist.
 String name = “Vijay”;
 try {
o System.out.println("Length of name is " + name.length());
o System.out.println("Charter at 7 position is " +
name.charAt(6));
 } catch (StringIndexOutOfBoundsException e) {
o System.out.println("String abhi choti he!!");
 } catch (RuntimeException e) {
o System.out.println(“Error “ + e,getMessage());
 }
www.SunilOS.com 19
www.SunilOS.com 20
System-Defined Exception
 It is raised implicitly by system because of illegal
execution of program when system cannot continue
program execution any more.
 It is created by Java System automatically.
 It is extended from Error class or RuntimeException class.
www.SunilOS.com 21
System-Defined Exception
 IndexOutOfBoundsException:
o When beyond the bound of index in the object which use index, such as
array, string, and vector.
 ArrayStoreException:
o When incorrect type of object is assigned to element of array.
 NegativeArraySizeException:
o When using a negative size of array.
 NullPointerException:
o When referring to object as a null pointer.
 SecurityException:
o When security is violated.
 IllegalMonitorStateException:
o When the thread which is not owner of monitor involves wait or notify
method.
www.SunilOS.com 22
Programmer-Defined Exception
Programmer can create
custom exceptions by
extending Exception or
its sub-classes.
Exceptions are raised by
programmer with help of
throw keyword.
Programmer Exception Class
 class LoginException extends Exception { //Custom exception
o public LoginException() {
• super("User Not Found");
o }
 }
 class UserClass { //Raise custom exception
 LoginException e = new LoginException();
 // ...
 if (val < 1) throw e;
 }
 }
 Exception is raised by throw keyword.
www.SunilOS.com 23
www.SunilOS.com 24
Exception Occurrence
Raises implicitly by system.
Raises explicitly by programmer.
Syntax: throw exceptionObject
throw new LoginException();
Throwable class or
its sub class
www.SunilOS.com 25
Exception propagation
 If there is no catch block to deal
with the exception, it is propagated
to calling method.
 Unchecked exceptions are
automatically propagated.
 Checked exceptions are propagated
by throws keyword.
 returntype methodName(params)
throws e1, ... ,ek { }
Called method
Calling method
Exception propagation ( Cont.)
 public static void main(String[] args) {
o try {
• authenticate (“vijay”);
o } catch (LoginException exp) {
• System.out.println(“Invalid Id/Passwod”);
o }
 }
 public static void authenticate ( String login) throws LoginException{
o If( !“admin”.equals(login)){
• LoginException e = new LoginException();
• throw e;
o }
 }
www.SunilOS.com 26
Disclaimer
This is an educational presentation to enhance the
skill of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are
used in this presentation to simplify technical
examples and correlate examples with the real
world.
We are grateful to owners of these URLs and
pictures.
www.SunilOS.com 27
Thank You!
www.SunilOS.com 28
www.SunilOS.com

More Related Content

What's hot

JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default MethodsHaim Michael
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 

What's hot (20)

JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Hibernate
Hibernate Hibernate
Hibernate
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Log4 J
Log4 JLog4 J
Log4 J
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
C Basics
C BasicsC Basics
C Basics
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
C++
C++C++
C++
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
 
PDBC
PDBCPDBC
PDBC
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
C# Basics
C# BasicsC# Basics
C# Basics
 
DJango
DJangoDJango
DJango
 

Viewers also liked

JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkVolker Hirsch
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionPritom Chaki
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in JavaQaziUmarF786
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFCSunil OS
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Layouts in android
Layouts in androidLayouts in android
Layouts in androidDurai S
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview QuestionsArc & Codementor
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...SlideShare
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShareSlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShareSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

Viewers also liked (17)

JavaScript
JavaScriptJavaScript
JavaScript
 
CSS
CSS CSS
CSS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of Work
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Layouts in android
Layouts in androidLayouts in android
Layouts in android
 
String Handling
String HandlingString Handling
String Handling
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to Exception Handling

Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 

Similar to Exception Handling (20)

Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 

More from Sunil OS

Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays TechnologiesSunil OS
 

More from Sunil OS (8)

OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C++ oop
C++ oopC++ oop
C++ oop
 

Recently uploaded

How to Manage Engineering to Order in Odoo 17
How to Manage Engineering to Order in Odoo 17How to Manage Engineering to Order in Odoo 17
How to Manage Engineering to Order in Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 

Recently uploaded (20)

How to Manage Engineering to Order in Odoo 17
How to Manage Engineering to Order in Odoo 17How to Manage Engineering to Order in Odoo 17
How to Manage Engineering to Order in Odoo 17
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 

Exception Handling

  • 2. www.SunilOS.com 2 Exception Exceptional (that is error) condition that has occurred in a piece of code of Java program.
  • 3. www.SunilOS.com 3 Exception  It will cause abnormal termination of program or wrong execution result.  Java provides an exception handling mechanism to handle exceptions.  Exception handling will improve the reliability of application program.  Java creates different type of objects in case of different exceptional conditions that describe the cause of exception.
  • 4. www.SunilOS.com 4 Exception Definition Treat exception as an object. All exceptions are instances of a class extended from Throwable class or its subclass. Generally, a programmer can make new exception class by extending the Exception class which is subclass of Throwable class.
  • 5. www.SunilOS.com 5 Hierarchical Structure of Throwable Class ObjectObject ThrowableThrowable ErrorError ExceptionException RuntimeExceptionRuntimeException ... ... ...
  • 6. www.SunilOS.com 6 Exception Types Error Class o Abnormal conditions those can NOT be handled are called Errors. Exception Class o Abnormal conditions those can be handled are called Exceptions.
  • 7. Java Exception class hierarchy www.SunilOS.com 7 ObjectObject Error ThrowableThrowable ExceptionException LinkageError VirtualMachoneError ClassNotFoundExceptionClassNotFoundException FileNotFoundExceptionFileNotFoundException IOExceptionIOException AWTError … AWTExceptionAWTException RuntimeException … ArithmeticException NullPointerException IndexOutOfBoundsException Unchecked CheckedChecked NoSuchElementException … : try-catch block is mandatory : try-catch block is optional
  • 8. www.SunilOS.com 8 Exception Handling  Exception handling is managed by five keywords try, catch, throw, throws, and finally.  Exceptions can be generated by o Java “run-time system” are called System-generated exceptions. It is automatically raised by Java run-time system. o Your code are called Programmatic Exceptions. It is raised by throw keyword.  When an exceptional condition arises, an object is created that contains exception description.  Handling is done with help of try-catch-finally block.  Exception raised in try block is caught by catch block.  Block finally is optional and always executed.
  • 9. www.SunilOS.com 9 try-catch-finally Statement  try {  // code  } catch (ExceptionType1 identifier) {  // alternate flow 1  } catch (ExceptionType2 identifier) {  // alternate flow 2  } finally {  //Resource release statements like close file ,  //close N/W connection,  //close Database connection, Release memory cache.  }
  • 10. Uncaught Exception  public class TestArithmetic {  public static void main(String[] args) { o int k = 0; o int i = 15; o double div = i / k; o System.out.println("Div is " + div);  }} www.SunilOS.com 10 Output java.lang.ArithmeticException: / by zero at TestArithmetic .main(TestArithmetic .java:5) JVM detects that number is divided by zero that will produce infinity. Since infinity can be stored that is why it makes a new exception object and then throws this exception. Output java.lang.ArithmeticException: / by zero at TestArithmetic .main(TestArithmetic .java:5) JVM detects that number is divided by zero that will produce infinity. Since infinity can be stored that is why it makes a new exception object and then throws this exception.
  • 11. Stack Trace Exception Output www.SunilOS.com 11 Exception class Exception Message Exception Line Number  JVM detects the attempt to divide by zero, it makes new exception object.  java.lang.ArithmeticException: / by zero  at TestArithmetic .main( TestArithmetic .java:5)
  • 12. Handle Exception  public class TestArithmetic {  public static void main(String[] args) { o int k = 0; int i = 15; o try { • double div = i / k; • System.out.println("Div is " + div); o } catch (ArithmeticException e) { • System.out.println(“Divided by Zero"); o }  }} www.SunilOS.com 12 Output Divided by Zero Notice that the call to println( ) inside the try block is never executed Output Divided by Zero Notice that the call to println( ) inside the try block is never executed
  • 13. Flow of execution • try { • a • b //Throw Exception • c • } catch (Exception e) { • d • e • } finally { • f • } Normal Flow a b c f Exceptional Flow  a b d e f www.SunilOS.com 13
  • 14. Exception methods  Object received in catch block contains two key methods o e.getMessage(); //displays error message. • / by zero o e.printStackTrace(); //displays complete trace of exception • java.lang.ArithmeticException: / by zero • at TestArithmetic .main( TestArithmetic .java:5) www.SunilOS.com 14
  • 15. Multiple catch blocks  More than one exception could be raised by a single try block. To handle this type of situation, you can specify two or more catch blocks.  String name = “Vijay”;  try { o System.out.println("Length of name is " + name.length()); o System.out.println("Charter at 7th position is " + name.charAt(6));  } catch (StringIndexOutOfBoundsException e) { o System.out.println("String abhi choti he!!");  } catch (NullPointerException e) { o System.out.println(“Sundar sa nam nahi he!");  } finally { o System.out.println(“Pandit hu me");  } www.SunilOS.com 15
  • 16. Multiple catch blocks (cont. )  More than one exception could be raised by a single try block. To handle this type of situation, you can specify two or more catch blocks.  String name = null;  try { o System.out.println("Length of name is " + name.length()); o System.out.println("Charter at 7th position is " + name.charAt(6));  } catch (StringIndexOutOfBoundsException e) { o System.out.println("String abhi choti he!!");  } catch (NullPointerException e) { o System.out.println(“Sundar sa nam nahi he!");  } finally { o System.out.println(“Pandit hu me");  } www.SunilOS.com 16
  • 17. Parent catch  String name = “Vijay”;  try { o System.out.println("Length of name is " + name.length()); o System.out.println("Charter at 7 position is " + name.charAt(6));  } catch (StringIndexOutOfBoundsException e) { o System.out.println("String abhi choti he!!");  } catch (RuntimeException e) { o System.out.println(“Sundar sa nam nahi he!");  } finally { o System.out.println(“Pandit hu me");  } www.SunilOS.com 17
  • 18. Generic Catch  A catch block of Parent Class can handle exceptions of its sub classes. It can be used as a generic catch to handle multiple exceptions in down hierarchy.  String name = “Vijay”;  try { o System.out.println("Length of name is " + name.length()); o System.out.println("Charter at 7th position is " + name.charAt(6));  } catch (Exception e) { o System.out.println(“Error ” + e.getMessage() );  } www.SunilOS.com 18
  • 19. Order of catch blocks: Parent & Child  Catch block of a Child class must come first in the order, if Parent’s class catch does exist.  String name = “Vijay”;  try { o System.out.println("Length of name is " + name.length()); o System.out.println("Charter at 7 position is " + name.charAt(6));  } catch (StringIndexOutOfBoundsException e) { o System.out.println("String abhi choti he!!");  } catch (RuntimeException e) { o System.out.println(“Error “ + e,getMessage());  } www.SunilOS.com 19
  • 20. www.SunilOS.com 20 System-Defined Exception  It is raised implicitly by system because of illegal execution of program when system cannot continue program execution any more.  It is created by Java System automatically.  It is extended from Error class or RuntimeException class.
  • 21. www.SunilOS.com 21 System-Defined Exception  IndexOutOfBoundsException: o When beyond the bound of index in the object which use index, such as array, string, and vector.  ArrayStoreException: o When incorrect type of object is assigned to element of array.  NegativeArraySizeException: o When using a negative size of array.  NullPointerException: o When referring to object as a null pointer.  SecurityException: o When security is violated.  IllegalMonitorStateException: o When the thread which is not owner of monitor involves wait or notify method.
  • 22. www.SunilOS.com 22 Programmer-Defined Exception Programmer can create custom exceptions by extending Exception or its sub-classes. Exceptions are raised by programmer with help of throw keyword.
  • 23. Programmer Exception Class  class LoginException extends Exception { //Custom exception o public LoginException() { • super("User Not Found"); o }  }  class UserClass { //Raise custom exception  LoginException e = new LoginException();  // ...  if (val < 1) throw e;  }  }  Exception is raised by throw keyword. www.SunilOS.com 23
  • 24. www.SunilOS.com 24 Exception Occurrence Raises implicitly by system. Raises explicitly by programmer. Syntax: throw exceptionObject throw new LoginException(); Throwable class or its sub class
  • 25. www.SunilOS.com 25 Exception propagation  If there is no catch block to deal with the exception, it is propagated to calling method.  Unchecked exceptions are automatically propagated.  Checked exceptions are propagated by throws keyword.  returntype methodName(params) throws e1, ... ,ek { } Called method Calling method
  • 26. Exception propagation ( Cont.)  public static void main(String[] args) { o try { • authenticate (“vijay”); o } catch (LoginException exp) { • System.out.println(“Invalid Id/Passwod”); o }  }  public static void authenticate ( String login) throws LoginException{ o If( !“admin”.equals(login)){ • LoginException e = new LoginException(); • throw e; o }  } www.SunilOS.com 26
  • 27. Disclaimer This is an educational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 27