SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil 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
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Hibernate
Hibernate Hibernate
Hibernate Sunil 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
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 

Was ist angesagt? (20)

JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
JDBC
JDBCJDBC
JDBC
 
Log4 J
Log4 JLog4 J
Log4 J
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
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
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Hibernate
Hibernate Hibernate
Hibernate
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
PDBC
PDBCPDBC
PDBC
 
DJango
DJangoDJango
DJango
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 

Andere mochten auch

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
 

Andere mochten auch (16)

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
 

Ähnlich wie Exception Handling

Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
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 Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
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
 

Ähnlich wie 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
 
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 Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling 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
 

Mehr von Sunil OS

Mehr von Sunil OS (9)

OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Angular 8
Angular 8 Angular 8
Angular 8
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C++ oop
C++ oopC++ oop
C++ oop
 
C++
C++C++
C++
 
C Basics
C BasicsC Basics
C Basics
 

Kürzlich hochgeladen

BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...Nguyen Thanh Tu Collection
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryEugene Lysak
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfbu07226
 
How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17Celine George
 
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Celine George
 
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Celine George
 
Behavioral-sciences-dr-mowadat rana (1).pdf
Behavioral-sciences-dr-mowadat rana (1).pdfBehavioral-sciences-dr-mowadat rana (1).pdf
Behavioral-sciences-dr-mowadat rana (1).pdfaedhbteg
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticspragatimahajan3
 
MichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfMichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfmstarkes24
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryCeline George
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/siemaillard
 
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatmentsaipooja36
 
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Mark Carrigan
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya - UEM Kolkata Quiz Club
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...Nguyen Thanh Tu Collection
 

Kürzlich hochgeladen (20)

BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17
 
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
 
Behavioral-sciences-dr-mowadat rana (1).pdf
Behavioral-sciences-dr-mowadat rana (1).pdfBehavioral-sciences-dr-mowadat rana (1).pdf
Behavioral-sciences-dr-mowadat rana (1).pdf
 
Word Stress rules esl .pptx
Word Stress rules esl               .pptxWord Stress rules esl               .pptx
Word Stress rules esl .pptx
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
MichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfMichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdf
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 Inventory
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdfPost Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
 

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