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 IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil 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
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in javaJayasankarPR2
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 

What's hot (20)

Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Hibernate
Hibernate Hibernate
Hibernate
 
Log4 J
Log4 JLog4 J
Log4 J
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Strings in java
Strings in javaStrings in java
Strings in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
C++ oop
C++ oopC++ oop
C++ oop
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Java I/O
Java I/OJava I/O
Java I/O
 
String in java
String in javaString in java
String in java
 

Viewers also liked

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
 
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 (15)

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
 
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
 
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
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 

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
 
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
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

More from Sunil OS

Threads v3
Threads v3Threads v3
Threads v3Sunil 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
 
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 (13)

DJango
DJangoDJango
DJango
 
PDBC
PDBCPDBC
PDBC
 
OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
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 )
 
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++
C++C++
C++
 
C Basics
C BasicsC Basics
C Basics
 

Recently uploaded

How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
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
 

Recently uploaded (20)

How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
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
 

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