SlideShare a Scribd company logo
EXCEPTION HANDLING
1RAJESHREE KHANDE
Errors
 Errors do occur in programming.
 Problems opening a file, dividing by zero, accessing
an out-of-bounds array element, hardware errors, and
many more
 The question becomes: What do we do when an error
occurs?
 How is the error handled?
 Who handles it?
 Should the program terminate?
 Can the program recover from the error?
 Java uses exceptions to provide the error-handling
2
RAJESHREE KHANDE
Exceptions
3
 Exceptions is condition that is caused by run-time error in program
 An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions.
 Represented as an object in Java
 Throwing an exception
 An error occurs within a method. An exception object is created
and handed off to the runtime system. The runtime system must
find the code to handle the error.
 Catching an exception
 The system searches for code to handle the thrown exception. It
can be in the same method or in some method in the call stack.RAJESHREE KHANDE
Types of Exception
4
RAJESHREE KHANDE
Checked Exceptions
 These are the exceptions which occur during the compile time
of the program.
 The compiler checks at the compile time that whether the
program contains handlers for checked exceptions or not.
 These exceptions do not extend RuntimeException class and
must be handled to avoid a compile-time error by the
programmer.
 These exceptions extend the java.lang.Exception
class These exceptional conditions should be anticipated and
recovered by an application.
5
RAJESHREE KHANDE
Checked Exceptions
 Furthermore Checked exceptions are required to be caught.
Remember that all the exceptions are checked exceptions unless and
until those indicated by Error, RuntimeException or their subclasses.
 For example if you call the readLine() method on a BufferedReader
object then the IOException may occur or if you want to build a
program that could read a file with a specific name then you would be
prompted to input a file name by the application. Then it passes the
name to the constructor for java.io.FileReader and opens the file.
However if you do not provide the name of any existing file then the
constructor throws java.io.FileNotFoundException which abrupt the
application to succeed. Hence this exception will be caught by a well-
written application and will also prompt to correct the file name.
6
RAJESHREE KHANDE
Checked Exceptions :Examples
 NoSuchFieldException InstantiationException
 IllegalAccessException
 ClassNotFoundException
 NoSuchMethodException
 CloneNotSupportedException
 InterruptedException
7
RAJESHREE KHANDE
Unchecked Exceptions
 Unchecked exceptions are the exceptions which occur during the
runtime of the program.
 Unchecked exceptions are internal to the application and extend the
java.lang.RuntimeException that is inherited from
java.lang.Exception class.
 These exceptions cannot be anticipated and recovered like
programming bugs, such as logic errors or improper use of an API.
 These type of exceptions are also called Runtime exceptions that
are usually caused by data errors, like arithmetic overflow, divide by
zero etc.
8
RAJESHREE KHANDE
Unchecked Exceptions :Examples
 IndexOutOfBoundsException ArrayIndexOutOfBoundsE
xception
 ClassCastException
 ArithmeticException
 NullPointerException
 IllegalStateException
 SecurityException
9
RAJESHREE KHANDE
Error
 The errors in java are external to the application.
 These are the exceptional conditions that could not be usually
anticipated by the application and also could not be recovered.
 Error exceptions belong to Error and its subclasses are not subject
to the catch or Specify requirement.
 Suppose a file is successfully opened by an application for input but
due to some system malfunction could not be able to read that file
then the java.io.IOError would be thrown.
 This error will cause the program to terminate but if an application
wants then the error might be caught.
 An Error indicates serious problems that a reasonable application
should not try to catch. Most such errors are abnormal conditions.
 Hence we can say that Errors and runtime exceptions are together
called as unchecked exceptions.
10
RAJESHREE KHANDE
Handling Exceptions
 Three statements help define how exceptions are
handled:
 try
identifies a block of statements within which an
exception might be thrown.
 catch
- must be associated with a try statement and identifies
a
block of statements that can handle a particular type of
exception.
- The statements are executed if an exception of a
particular
11
RAJESHREE KHANDE
Handling Exceptions
 finally –
- must be associated with a try statement and
identifies a block of statements that are
executed regardless of whether or not an
error occurs within the try block.
- Even if the try and catch block have a
return statement in them, finally will still run.
12
RAJESHREE KHANDE
Handling Exceptions
try Block
catch Block
Exception object
creator
Exception handler
Stmt. that cause
an exception
Stmt. that handles
the exception
Throws
Exception
Object
13
RAJESHREE KHANDE
Handling Exceptions
 General form:
try
{
statement(s);
}
catch (ExceptionType name)
{
statement(s);
}
finally
{
statement(s);
}
14
RAJESHREE KHANDE
Exception Class Hierarchy
 Java has a predefined set of exceptions and errors that
can occur during execution.
Exception (derived from Throwable)
ClassNotFoundException
ArithmeticException
IndexOutOfBoundsException
NullPointerException
IOExceptionRunTimeException
This is just a small part
of the Exception
hierarchy
NumberFormatException
15
RAJESHREE KHANDE
Common Java Exception
Exception Type Cause of Exception
ArithmaticException Caused by math errors such as division by
Zero
ArrayIndexOutOfBoundException Caused by bad array indexes
ArrayStoreException Caused when a program tries to store the
wrong type of data in array
FileNotFoundException Attempt to access a nonexistent file
IOException Caused by general IO failure such as
inability to read a file
NullPointerException Caused by referencing a Null Object
NumberFormatException Caused when conversion between string
and number fails
16
RAJESHREE KHANDE
Common Java Exception
Exception Type Cause of Exception
OUtOfMemoryException Caused by when there is no enough
memory to allocate a new object
SecurityException Caused when applet tries to perform an
action not allowed by the Brower's security
setting
StackOverFlowException Caused when the system runs out of Stack
space
StringIndexOutOfBOundException Caused when program attempt to access a
nonexistent position in string
17
RAJESHREE KHANDE
 Program did not stop at the point of Exceptional
condition
 It catches the error condition, print the error
messages and then continue the execution
18
RAJESHREE KHANDE
Multiple catch Statement
 It is possible to have more than one catch statement in
catch block.
 Works similar to switch statement
 Java does not require any processing at all
 We can simpliy have an empty block to avoid program
abortion.
catch (Exception e);  catch an exception and
ignore it.
19
RAJESHREE KHANDE
-------
------
try
{
-----
}
catch (Exception-Type 1)
{
------
}
catch (Exception-Type 2)
{
-----
}
.
.
.
catch (Exception-Type n)
{
--------
}
20
RAJESHREE KHANDE
 It is also possible to throw an exception using throw statement
 Synatax
Example :
throw new ArithmaticException();
throw new NumberFormatException
1 All exception object is created by using new operator
or simply parameter to catch block
throw new throwable_subclass;
The throw Keyword
21
RAJESHREE KHANDE
The throw Keyword
 For throwing an exception we have to do
1. create an instance an object which is subclass of
java.lang.Throwable
2. Use throw keyword to throw an exception
Example:
throw new IOException(“file not found”);
- After throw stmt. The nearest enclosing try block is
checked to see it has the catch block that matches
the type of exception.
- If match is found control is transfer to that catch block.
- If not matches with anyone of the specified catch clause
the default exception handler halts the program and
print he stack trace.
22
RAJESHREE KHANDE
Difference between throw and throws
keywords
 Whenever we want to force an exception then we use
throw keyword.
 The throw keyword is used to force an exception.
 Moreover throw keyword can also be used to pass a
custom message to the exception handling module i.e.
the message which we want to be printed. For example
throw new MyException ("can't be divided by zero");
23
RAJESHREE KHANDE
throws
 Whereas when we know that a particular exception may be
thrown or to pass a possible exception then we use throws
keyword.
 The Java compiler very well knows about the exceptions
thrown by some methods so it insists us to handle them
 We can also use throws clause on the surrounding
method instead of try and catch exception handler. For
Example.
static int divide(int first,int second) throws MyException{
24
RAJESHREE KHANDE
Creating our own Exceptions
 Two reasons for defining our own Exception
1 If you want to add additional information if standard
exception occur.
2 You may have error condition that arise in your code
 To create your own Exception define a subclass of
Exception, Which is subclass of Throwable.
 All method define by throwable class can be available in
that subclass so we may override this methods.
25
RAJESHREE KHANDE
Creating our own Exceptions
 Some of methods defined by Class throwable
 Example
Sr.
No
Method Description
1 getMessage() Returns a Description of the Exception
2 getStackTrace() Returns an array that contain the stack
3 printStackTrace() Display the stack trace
4 toString Returns a string object containing a
description of the exception
26
RAJESHREE KHANDE

More Related Content

What's hot (19)

PPTX
Exception Handling in Java
lalithambiga kamaraj
 
PPT
Java: Exception
Tareq Hasan
 
PPT
Exception handling
Tata Consultancy Services
 
PPTX
Z blue exception
Narayana Swamy
 
PPT
Exception Handling Java
ankitgarg_er
 
PDF
Creating your own exception
TharuniDiddekunta
 
PDF
Exception handling basic
TharuniDiddekunta
 
PPTX
Exception handling
Ardhendu Nandi
 
PPTX
Event handling
Mohamed Essam
 
PPTX
Java Exception Handling
GovindanS3
 
ODP
Exception Handling In Java
parag
 
PPTX
Exceptions overview
Bharath K
 
PPTX
Exception handling in java
Adil Mehmoood
 
PPT
Exception handling in java
AmbigaMurugesan
 
PPT
12 exception handling
Arriz San Juan
 
PPTX
Exception handling in Java
Ankit Rai
 
PPTX
Exception handling in Java
Prasad Sawant
 
PDF
Python exception handling
Mohammed Sikander
 
PDF
Exception handling
Garuda Trainings
 
Exception Handling in Java
lalithambiga kamaraj
 
Java: Exception
Tareq Hasan
 
Exception handling
Tata Consultancy Services
 
Z blue exception
Narayana Swamy
 
Exception Handling Java
ankitgarg_er
 
Creating your own exception
TharuniDiddekunta
 
Exception handling basic
TharuniDiddekunta
 
Exception handling
Ardhendu Nandi
 
Event handling
Mohamed Essam
 
Java Exception Handling
GovindanS3
 
Exception Handling In Java
parag
 
Exceptions overview
Bharath K
 
Exception handling in java
Adil Mehmoood
 
Exception handling in java
AmbigaMurugesan
 
12 exception handling
Arriz San Juan
 
Exception handling in Java
Ankit Rai
 
Exception handling in Java
Prasad Sawant
 
Python exception handling
Mohammed Sikander
 
Exception handling
Garuda Trainings
 

Similar to Java Exceptions Handling (20)

PPTX
Exception handling in java
pooja kumari
 
PPTX
Exception handling in java
pooja kumari
 
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
PPTX
Interface andexceptions
saman Iftikhar
 
PPTX
Exception handling in java
Elizabeth alexander
 
PDF
Java unit 11
Shipra Swati
 
PPTX
java exception.pptx
SukhpreetSingh519414
 
PDF
16 exception handling - i
Ravindra Rathore
 
PPT
Exception and ErrorHandling in Java .ppt
JyothiAmpally
 
PPTX
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
PPT
Exceptions in java
Manav Prasad
 
PDF
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
PPT
exceptions in java
javeed_mhd
 
PPTX
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
PPTX
Java exception handling
Md. Tanvir Hossain
 
PPTX
EXCEPTION HANDLING in prograaming
MuskanNazeer
 
PPT
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
PPTX
Exceptions handling in java
junnubabu
 
PPTX
L14 exception handling
teach4uin
 
PDF
Java exception handling ppt
JavabynataraJ
 
Exception handling in java
pooja kumari
 
Exception handling in java
pooja kumari
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Interface andexceptions
saman Iftikhar
 
Exception handling in java
Elizabeth alexander
 
Java unit 11
Shipra Swati
 
java exception.pptx
SukhpreetSingh519414
 
16 exception handling - i
Ravindra Rathore
 
Exception and ErrorHandling in Java .ppt
JyothiAmpally
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
Exceptions in java
Manav Prasad
 
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
exceptions in java
javeed_mhd
 
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Java exception handling
Md. Tanvir Hossain
 
EXCEPTION HANDLING in prograaming
MuskanNazeer
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Exceptions handling in java
junnubabu
 
L14 exception handling
teach4uin
 
Java exception handling ppt
JavabynataraJ
 
Ad

More from DrRajeshreeKhande (20)

PPTX
.NET F# Inheritance and operator overloading
DrRajeshreeKhande
 
PPTX
Exception Handling in .NET F#
DrRajeshreeKhande
 
PPTX
.NET F# Events
DrRajeshreeKhande
 
PPTX
.NET F# Class constructor
DrRajeshreeKhande
 
PPTX
.NET F# Abstract class interface
DrRajeshreeKhande
 
PPTX
.Net F# Generic class
DrRajeshreeKhande
 
PPTX
F# Console class
DrRajeshreeKhande
 
PPTX
.net F# mutable dictionay
DrRajeshreeKhande
 
PPTX
F sharp lists & dictionary
DrRajeshreeKhande
 
PPTX
F# array searching
DrRajeshreeKhande
 
PPTX
Net (f#) array
DrRajeshreeKhande
 
PPTX
.Net (F # ) Records, lists
DrRajeshreeKhande
 
PPT
MS Office for Beginners
DrRajeshreeKhande
 
PPSX
Java Multi-threading programming
DrRajeshreeKhande
 
PPSX
Java String class
DrRajeshreeKhande
 
PPTX
JAVA AWT components
DrRajeshreeKhande
 
PPSX
Dr. Rajeshree Khande :Introduction to Java AWT
DrRajeshreeKhande
 
PPSX
Dr. Rajeshree Khande Java Interactive input
DrRajeshreeKhande
 
PPSX
Dr. Rajeshree Khande :Intoduction to java
DrRajeshreeKhande
 
PPSX
Dr. Rajeshree Khande : Java Basics
DrRajeshreeKhande
 
.NET F# Inheritance and operator overloading
DrRajeshreeKhande
 
Exception Handling in .NET F#
DrRajeshreeKhande
 
.NET F# Events
DrRajeshreeKhande
 
.NET F# Class constructor
DrRajeshreeKhande
 
.NET F# Abstract class interface
DrRajeshreeKhande
 
.Net F# Generic class
DrRajeshreeKhande
 
F# Console class
DrRajeshreeKhande
 
.net F# mutable dictionay
DrRajeshreeKhande
 
F sharp lists & dictionary
DrRajeshreeKhande
 
F# array searching
DrRajeshreeKhande
 
Net (f#) array
DrRajeshreeKhande
 
.Net (F # ) Records, lists
DrRajeshreeKhande
 
MS Office for Beginners
DrRajeshreeKhande
 
Java Multi-threading programming
DrRajeshreeKhande
 
Java String class
DrRajeshreeKhande
 
JAVA AWT components
DrRajeshreeKhande
 
Dr. Rajeshree Khande :Introduction to Java AWT
DrRajeshreeKhande
 
Dr. Rajeshree Khande Java Interactive input
DrRajeshreeKhande
 
Dr. Rajeshree Khande :Intoduction to java
DrRajeshreeKhande
 
Dr. Rajeshree Khande : Java Basics
DrRajeshreeKhande
 
Ad

Recently uploaded (20)

PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
Horarios de distribución de agua en julio
pegazohn1978
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 

Java Exceptions Handling

  • 2. Errors  Errors do occur in programming.  Problems opening a file, dividing by zero, accessing an out-of-bounds array element, hardware errors, and many more  The question becomes: What do we do when an error occurs?  How is the error handled?  Who handles it?  Should the program terminate?  Can the program recover from the error?  Java uses exceptions to provide the error-handling 2 RAJESHREE KHANDE
  • 3. Exceptions 3  Exceptions is condition that is caused by run-time error in program  An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.  Represented as an object in Java  Throwing an exception  An error occurs within a method. An exception object is created and handed off to the runtime system. The runtime system must find the code to handle the error.  Catching an exception  The system searches for code to handle the thrown exception. It can be in the same method or in some method in the call stack.RAJESHREE KHANDE
  • 5. Checked Exceptions  These are the exceptions which occur during the compile time of the program.  The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not.  These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer.  These exceptions extend the java.lang.Exception class These exceptional conditions should be anticipated and recovered by an application. 5 RAJESHREE KHANDE
  • 6. Checked Exceptions  Furthermore Checked exceptions are required to be caught. Remember that all the exceptions are checked exceptions unless and until those indicated by Error, RuntimeException or their subclasses.  For example if you call the readLine() method on a BufferedReader object then the IOException may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. Then it passes the name to the constructor for java.io.FileReader and opens the file. However if you do not provide the name of any existing file then the constructor throws java.io.FileNotFoundException which abrupt the application to succeed. Hence this exception will be caught by a well- written application and will also prompt to correct the file name. 6 RAJESHREE KHANDE
  • 7. Checked Exceptions :Examples  NoSuchFieldException InstantiationException  IllegalAccessException  ClassNotFoundException  NoSuchMethodException  CloneNotSupportedException  InterruptedException 7 RAJESHREE KHANDE
  • 8. Unchecked Exceptions  Unchecked exceptions are the exceptions which occur during the runtime of the program.  Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class.  These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API.  These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc. 8 RAJESHREE KHANDE
  • 9. Unchecked Exceptions :Examples  IndexOutOfBoundsException ArrayIndexOutOfBoundsE xception  ClassCastException  ArithmeticException  NullPointerException  IllegalStateException  SecurityException 9 RAJESHREE KHANDE
  • 10. Error  The errors in java are external to the application.  These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered.  Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement.  Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.IOError would be thrown.  This error will cause the program to terminate but if an application wants then the error might be caught.  An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.  Hence we can say that Errors and runtime exceptions are together called as unchecked exceptions. 10 RAJESHREE KHANDE
  • 11. Handling Exceptions  Three statements help define how exceptions are handled:  try identifies a block of statements within which an exception might be thrown.  catch - must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. - The statements are executed if an exception of a particular 11 RAJESHREE KHANDE
  • 12. Handling Exceptions  finally – - must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block. - Even if the try and catch block have a return statement in them, finally will still run. 12 RAJESHREE KHANDE
  • 13. Handling Exceptions try Block catch Block Exception object creator Exception handler Stmt. that cause an exception Stmt. that handles the exception Throws Exception Object 13 RAJESHREE KHANDE
  • 14. Handling Exceptions  General form: try { statement(s); } catch (ExceptionType name) { statement(s); } finally { statement(s); } 14 RAJESHREE KHANDE
  • 15. Exception Class Hierarchy  Java has a predefined set of exceptions and errors that can occur during execution. Exception (derived from Throwable) ClassNotFoundException ArithmeticException IndexOutOfBoundsException NullPointerException IOExceptionRunTimeException This is just a small part of the Exception hierarchy NumberFormatException 15 RAJESHREE KHANDE
  • 16. Common Java Exception Exception Type Cause of Exception ArithmaticException Caused by math errors such as division by Zero ArrayIndexOutOfBoundException Caused by bad array indexes ArrayStoreException Caused when a program tries to store the wrong type of data in array FileNotFoundException Attempt to access a nonexistent file IOException Caused by general IO failure such as inability to read a file NullPointerException Caused by referencing a Null Object NumberFormatException Caused when conversion between string and number fails 16 RAJESHREE KHANDE
  • 17. Common Java Exception Exception Type Cause of Exception OUtOfMemoryException Caused by when there is no enough memory to allocate a new object SecurityException Caused when applet tries to perform an action not allowed by the Brower's security setting StackOverFlowException Caused when the system runs out of Stack space StringIndexOutOfBOundException Caused when program attempt to access a nonexistent position in string 17 RAJESHREE KHANDE
  • 18.  Program did not stop at the point of Exceptional condition  It catches the error condition, print the error messages and then continue the execution 18 RAJESHREE KHANDE
  • 19. Multiple catch Statement  It is possible to have more than one catch statement in catch block.  Works similar to switch statement  Java does not require any processing at all  We can simpliy have an empty block to avoid program abortion. catch (Exception e);  catch an exception and ignore it. 19 RAJESHREE KHANDE
  • 20. ------- ------ try { ----- } catch (Exception-Type 1) { ------ } catch (Exception-Type 2) { ----- } . . . catch (Exception-Type n) { -------- } 20 RAJESHREE KHANDE
  • 21.  It is also possible to throw an exception using throw statement  Synatax Example : throw new ArithmaticException(); throw new NumberFormatException 1 All exception object is created by using new operator or simply parameter to catch block throw new throwable_subclass; The throw Keyword 21 RAJESHREE KHANDE
  • 22. The throw Keyword  For throwing an exception we have to do 1. create an instance an object which is subclass of java.lang.Throwable 2. Use throw keyword to throw an exception Example: throw new IOException(“file not found”); - After throw stmt. The nearest enclosing try block is checked to see it has the catch block that matches the type of exception. - If match is found control is transfer to that catch block. - If not matches with anyone of the specified catch clause the default exception handler halts the program and print he stack trace. 22 RAJESHREE KHANDE
  • 23. Difference between throw and throws keywords  Whenever we want to force an exception then we use throw keyword.  The throw keyword is used to force an exception.  Moreover throw keyword can also be used to pass a custom message to the exception handling module i.e. the message which we want to be printed. For example throw new MyException ("can't be divided by zero"); 23 RAJESHREE KHANDE
  • 24. throws  Whereas when we know that a particular exception may be thrown or to pass a possible exception then we use throws keyword.  The Java compiler very well knows about the exceptions thrown by some methods so it insists us to handle them  We can also use throws clause on the surrounding method instead of try and catch exception handler. For Example. static int divide(int first,int second) throws MyException{ 24 RAJESHREE KHANDE
  • 25. Creating our own Exceptions  Two reasons for defining our own Exception 1 If you want to add additional information if standard exception occur. 2 You may have error condition that arise in your code  To create your own Exception define a subclass of Exception, Which is subclass of Throwable.  All method define by throwable class can be available in that subclass so we may override this methods. 25 RAJESHREE KHANDE
  • 26. Creating our own Exceptions  Some of methods defined by Class throwable  Example Sr. No Method Description 1 getMessage() Returns a Description of the Exception 2 getStackTrace() Returns an array that contain the stack 3 printStackTrace() Display the stack trace 4 toString Returns a string object containing a description of the exception 26 RAJESHREE KHANDE