SlideShare a Scribd company logo
1 of 27
Ranjitha M
Department of Computer Science [PG]
Kristu jayanti College[Autonomous]
Bengaluru
Exceptions in Java
10-2
Exceptions
10-3
Exceptions
• An exception is an object that describes an
unusual or erroneous situation
• Exceptions are thrown by a program, and may be
caught and handled by another part of the
program
• A program can be separated into a normal
execution flow and an exception execution flow
• An error is also represented as an object in Java,
but usually represents a unrecoverable situation
and should not be caught
10-4
Exception Handling
• Java has a predefined set of exceptions and errors
that can occur during execution
• A program can deal with an exception in one of
three ways:
 ignore it
 handle it where it occurs
 handle it an another place in the program
• The manner in which an exception is processed is
an important design consideration
10-5
Exception Handling
• If an exception is ignored by the program, the
program will terminate abnormally and produce
an appropriate message
• The message includes a call stack trace that:
 indicates the line on which the exception occurred
 shows the method call trail that lead to the attempted
execution of the offending line
GENERAL FORM
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
} 10-6
10-7
The try Statement
• To handle an exception in a program, the line that
throws the exception is executed within a try block
• A try block is followed by one or more catch
clauses
• Each catch clause has an associated exception
type and is called an exception handler
• When an exception occurs, processing continues
at the first catch clause that matches the
exception type
10-8
The finally Clause
• A try statement can have an optional clause
following the catch clauses, designated by the
reserved word finally
• The statements in the finally clause always are
executed
• If no exception is generated, the statements in the
finally clause are executed after the statements in
the try block complete
• If an exception is generated, the statements in the
finally clause are executed after the statements in
the appropriate catch clause complete
Keyword Description
try The "try" keyword is used to specify a block where we
should place exception code. The try block must be
followed by either catch or finally. It means, we can't use
try block alone.
catch The "catch" block is used to handle the exception. It
must be preceded by try block which means we can't use
catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the important code
of the program. It is executed whether an exception is
handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It
doesn't throw an exception. It specifies that there may
occur an exception in the method. It is always used with
method signature.
10-9
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
10-10
Exception Propagation
• An exception can be handled at a higher level if it
is not appropriate to handle it where it occurs
• Exceptions propagate up through the method
calling hierarchy until they are caught and handled
or until they reach the level of the main method
• A try block that contains a call to a method in
which an exception is thrown can be used to catch
that exception
Exception Types
10-11
Throwable // main class
1. Exception
1.1 RuntimeException
2. Error
© 2004 Pearson Addison-Wesley. All rights reserved 10-12
10-13
The Exception Class Hierarchy
• Classes that define exceptions are related by
inheritance, forming an exception class hierarchy
• All error and exception classes are descendents of
the Throwable class
• A programmer can define an exception by
extending the Exception class or one of its
descendants
• The parent class used depends on how the new
exception will be used
10-14
Checked Exceptions
• An exception is either checked or unchecked
• A checked exception either must be caught by a
method, or must be listed in the throws clause of
any method that may throw or propagate it
• A throws clause is appended to the method header
• The compiler will issue an error if a checked
exception is not caught or asserted in a throws
clause
10-15
Unchecked Exceptions
• An unchecked exception does not require explicit
handling, though it could be processed that way
• The only unchecked exceptions in Java are
objects of type RuntimeException or any of its
descendants
• Errors are similar to RuntimeException and its
descendants in that:
 Errors should not be caught
 Errors do not require a throws clause
1. Arithmetic Exception
It is thrown when an exceptional condition has occurred in an
arithmetic operation.
2. ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or
equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose
definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not
open.
5. IOException
It is thrown when an input-output operation failed or interrupted
10-16
Built-in Exceptions
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some
processing , and it is interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable)
specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object.
Null represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into
a numeric format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either
negative than the size of the string
10-17
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
} } 10-18
// Handle an exception and move on.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e)
{
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}}} 10-19
Multiple catch
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e)
{System.out.println("common task completed");}
System.out.println("rest of the code...");
}
} 10-20
Nested try
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
} catch(ArithmeticException e) {System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
} catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);}
System.out.println("other statement);
} catch(Exception e) {System.out.println("handeled");}
System.out.println("normal flow..");
}
} 10-21
10-22
The throw Statement
• it is possible for your program to throw an exception explicitly, using
the throw statement.
• The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.
• Exceptions are thrown using the throw statement
• Usually a throw statement is executed inside an if statement that
evaluates a condition to see if the exception should be thrown.
• The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed. The nearest enclosing
try block is inspected to see if it has a catch statement that matches
the type of exception. If it does find a match, control is transferred to
that statement. If not, then the next enclosing try statement is
inspected, and so on. If no matching catch is found, then the default
exception handler halts the program and prints the stack trace.
// Java program that demonstrates the use of throw
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
} } } 10-23
Throws
If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard
themselves against that exception. You do this by including a throws clause
in the method’s declaration. A throws clause lists the typesof exceptions that
a method might throw. This is necessary for all exceptions, except those of
type Error or RuntimeException, or any of their subclasses. All other
exceptions that a method can throw must be declared in the throws clause.
If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws
clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a
method can throw.
10-24
Example - throws
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
10-25
Finally Block
• The finally block follows a try block or a catch block. A
finally block of code always executes, irrespective of
occurrence of an Exception.
• Using a finally block allows you to run any cleanup-type
statements that you want to execute, no matter what
happens in the protected code.
10-26
Finally example
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
10-27

More Related Content

Similar to Java Exception.ppt

Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
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 MultithreadingSakkaravarthiS1
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception HandlingAshwin Shiv
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11Terry Yoast
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 

Similar to Java Exception.ppt (20)

Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
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
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
exception handling
exception handlingexception handling
exception handling
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
 
Chap12
Chap12Chap12
Chap12
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception 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
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 

More from RanjithaM32

Various types of File Operations in Java
Various types of  File Operations in JavaVarious types of  File Operations in Java
Various types of File Operations in JavaRanjithaM32
 
Unit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptxUnit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptxRanjithaM32
 
Unit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxUnit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxRanjithaM32
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptxRanjithaM32
 
ARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxRanjithaM32
 
Html introduction
Html introductionHtml introduction
Html introductionRanjithaM32
 
Types of learning
Types of learningTypes of learning
Types of learningRanjithaM32
 
Knowledge base system
Knowledge base systemKnowledge base system
Knowledge base systemRanjithaM32
 

More from RanjithaM32 (13)

svm.ppt
svm.pptsvm.ppt
svm.ppt
 
Various types of File Operations in Java
Various types of  File Operations in JavaVarious types of  File Operations in Java
Various types of File Operations in Java
 
Unit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptxUnit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptx
 
Unit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxUnit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptx
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
ARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptx
 
Lisp.pptx
Lisp.pptxLisp.pptx
Lisp.pptx
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Html introduction
Html introductionHtml introduction
Html introduction
 
Threads
ThreadsThreads
Threads
 
Types of learning
Types of learningTypes of learning
Types of learning
 
Ml introduction
Ml introductionMl introduction
Ml introduction
 
Knowledge base system
Knowledge base systemKnowledge base system
Knowledge base system
 

Recently uploaded

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 

Recently uploaded (20)

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 

Java Exception.ppt

  • 1. Ranjitha M Department of Computer Science [PG] Kristu jayanti College[Autonomous] Bengaluru Exceptions in Java
  • 3. 10-3 Exceptions • An exception is an object that describes an unusual or erroneous situation • Exceptions are thrown by a program, and may be caught and handled by another part of the program • A program can be separated into a normal execution flow and an exception execution flow • An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught
  • 4. 10-4 Exception Handling • Java has a predefined set of exceptions and errors that can occur during execution • A program can deal with an exception in one of three ways:  ignore it  handle it where it occurs  handle it an another place in the program • The manner in which an exception is processed is an important design consideration
  • 5. 10-5 Exception Handling • If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message • The message includes a call stack trace that:  indicates the line on which the exception occurred  shows the method call trail that lead to the attempted execution of the offending line
  • 6. GENERAL FORM try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed after try block ends } 10-6
  • 7. 10-7 The try Statement • To handle an exception in a program, the line that throws the exception is executed within a try block • A try block is followed by one or more catch clauses • Each catch clause has an associated exception type and is called an exception handler • When an exception occurs, processing continues at the first catch clause that matches the exception type
  • 8. 10-8 The finally Clause • A try statement can have an optional clause following the catch clauses, designated by the reserved word finally • The statements in the finally clause always are executed • If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete • If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete
  • 9. Keyword Description try The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature. 10-9 Java Exception Keywords There are 5 keywords which are used in handling exceptions in Java.
  • 10. 10-10 Exception Propagation • An exception can be handled at a higher level if it is not appropriate to handle it where it occurs • Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method • A try block that contains a call to a method in which an exception is thrown can be used to catch that exception
  • 11. Exception Types 10-11 Throwable // main class 1. Exception 1.1 RuntimeException 2. Error
  • 12. © 2004 Pearson Addison-Wesley. All rights reserved 10-12
  • 13. 10-13 The Exception Class Hierarchy • Classes that define exceptions are related by inheritance, forming an exception class hierarchy • All error and exception classes are descendents of the Throwable class • A programmer can define an exception by extending the Exception class or one of its descendants • The parent class used depends on how the new exception will be used
  • 14. 10-14 Checked Exceptions • An exception is either checked or unchecked • A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it • A throws clause is appended to the method header • The compiler will issue an error if a checked exception is not caught or asserted in a throws clause
  • 15. 10-15 Unchecked Exceptions • An unchecked exception does not require explicit handling, though it could be processed that way • The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants • Errors are similar to RuntimeException and its descendants in that:  Errors should not be caught  Errors do not require a throws clause
  • 16. 1. Arithmetic Exception It is thrown when an exceptional condition has occurred in an arithmetic operation. 2. ArrayIndexOutOfBoundException It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. 3. ClassNotFoundException This Exception is raised when we try to access a class whose definition is not found 4. FileNotFoundException This Exception is raised when a file is not accessible or does not open. 5. IOException It is thrown when an input-output operation failed or interrupted 10-16 Built-in Exceptions
  • 17. 6. InterruptedException It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted. 7. NoSuchFieldException It is thrown when a class does not contain the field (or variable) specified 8. NoSuchMethodException It is thrown when accessing a method which is not found. 9. NullPointerException This exception is raised when referring to the members of a null object. Null represents nothing 10. NumberFormatException This exception is raised when a method could not convert a string into a numeric format. 11. RuntimeException This represents any exception which occurs during runtime. 12. StringIndexOutOfBoundsException It is thrown by String class methods to indicate that an index is either negative than the size of the string 10-17
  • 18. // Java program to demonstrate ArithmeticException class ArithmeticException_Demo { public static void main(String args[]) { try { int a = 30, b = 0; int c = a/b; // cannot divide by zero System.out.println ("Result = " + c); } catch(ArithmeticException e) { System.out.println ("Can't divide a number by 0"); } } } 10-18
  • 19. // Handle an exception and move on. import java.util.Random; class HandleError { public static void main(String args[]) { int a=0, b=0, c=0; Random r = new Random(); for(int i=0; i<32000; i++) { try { b = r.nextInt(); c = r.nextInt(); a = 12345 / (b/c); } catch (ArithmeticException e) { System.out.println("Division by zero."); a = 0; // set a to zero and continue } System.out.println("a: " + a); }}} 10-19
  • 20. Multiple catch public class TestMultipleCatchBlock{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) {System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e) {System.out.println("task 2 completed");} catch(Exception e) {System.out.println("common task completed");} System.out.println("rest of the code..."); } } 10-20
  • 21. Nested try class Excep6{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; } catch(ArithmeticException e) {System.out.println(e);} try{ int a[]=new int[5]; a[5]=4; } catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);} System.out.println("other statement); } catch(Exception e) {System.out.println("handeled");} System.out.println("normal flow.."); } } 10-21
  • 22. 10-22 The throw Statement • it is possible for your program to throw an exception explicitly, using the throw statement. • The general form of throw is shown here: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. • Exceptions are thrown using the throw statement • Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown. • The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
  • 23. // Java program that demonstrates the use of throw class ThrowExcep { static void fun() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside fun()."); throw e; // rethrowing the exception } } } } 10-23
  • 24. Throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the typesof exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw. 10-24
  • 25. Example - throws class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } Here is the output generated by running this example program: inside throwOne caught java.lang.IllegalAccessException: demo 10-25
  • 26. Finally Block • The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. • Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. 10-26
  • 27. Finally example public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); }finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } 10-27