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

Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
Creating your own exception
Creating your own exceptionCreating your own exception
Creating your own exception
TharuniDiddekunta
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
TharuniDiddekunta
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Event handling
Event handlingEvent handling
Event handling
Mohamed Essam
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil Mehmoood
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
Arriz San Juan
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 

What's hot (19)

Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Creating your own exception
Creating your own exceptionCreating your own exception
Creating your own exception
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Exception handling
Exception handlingException handling
Exception handling
 
Event handling
Event handlingEvent handling
Event handling
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
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
 
12 exception handling
12 exception handling12 exception handling
12 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
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 

Similar to Java Exceptions

Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
arnold 7490
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
Java Programming
 
VTU MCA 2022 JAVA Exceeption Handling.docx
VTU MCA  2022 JAVA Exceeption Handling.docxVTU MCA  2022 JAVA Exceeption Handling.docx
VTU MCA 2022 JAVA Exceeption Handling.docx
Poornima E.G.
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Java Exception Handling and examples about it
Java Exception Handling and examples about itJava Exception Handling and examples about it
Java Exception Handling and examples about it
2022002857mbit
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
Swabhav Techlabs
 
summarizer16fev16_Exceptions
summarizer16fev16_Exceptionssummarizer16fev16_Exceptions
summarizer16fev16_Exceptions
Filipe Morais Jorge
 
Exception handling.pptx
Exception handling.pptxException handling.pptx
Exception handling.pptx
NISHASOMSCS113
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Garuda Trainings
 

Similar to Java Exceptions (20)

Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
 
VTU MCA 2022 JAVA Exceeption Handling.docx
VTU MCA  2022 JAVA Exceeption Handling.docxVTU MCA  2022 JAVA Exceeption Handling.docx
VTU MCA 2022 JAVA Exceeption Handling.docx
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
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
Exception handlingException handling
Exception handling
 
Java Exception Handling and examples about it
Java Exception Handling and examples about itJava Exception Handling and examples about it
Java Exception Handling and examples about it
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
 
summarizer16fev16_Exceptions
summarizer16fev16_Exceptionssummarizer16fev16_Exceptions
summarizer16fev16_Exceptions
 
Exception handling.pptx
Exception handling.pptxException handling.pptx
Exception handling.pptx
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 

Recently uploaded

Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
Kavitha Krishnan
 

Recently uploaded (20)

Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
 

Java Exceptions

  • 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