SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Tendances (20)

Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Log4 J
Log4 JLog4 J
Log4 J
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Hibernate
Hibernate Hibernate
Hibernate
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
C++ oop
C++ oopC++ oop
C++ oop
 
Java collections
Java collectionsJava collections
Java collections
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
CSS
CSS CSS
CSS
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
C# in depth
C# in depthC# in depth
C# in depth
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
C++
C++C++
C++
 

En vedette

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
 

En vedette (15)

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
 

Similaire à Exception Handling

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 

Similaire à 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
 

Plus de Sunil OS (12)

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 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C Basics
C BasicsC Basics
C Basics
 

Dernier

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Dernier (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

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