SlideShare uma empresa Scribd logo
1 de 27
Baixar para ler offline
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

Mais conteúdo relacionado

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

A brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProA brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProRay Yuan Liu
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxStephen Sitton
 
Secure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech LabsSecure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech Labsamber724300
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...arifengg7
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.elesangwon
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
priority interrupt computer organization
priority interrupt computer organizationpriority interrupt computer organization
priority interrupt computer organizationchnrketan
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTSneha Padhiar
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSneha Padhiar
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
AntColonyOptimizationManetNetworkAODV.pptx
AntColonyOptimizationManetNetworkAODV.pptxAntColonyOptimizationManetNetworkAODV.pptx
AntColonyOptimizationManetNetworkAODV.pptxLina Kadam
 
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfModule-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfManish Kumar
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESkarthi keyan
 
Novel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsNovel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsResearcher Researcher
 
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork
 
Substation Automation SCADA and Gateway Solutions by BRH
Substation Automation SCADA and Gateway Solutions by BRHSubstation Automation SCADA and Gateway Solutions by BRH
Substation Automation SCADA and Gateway Solutions by BRHbirinder2
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical trainingGladiatorsKasper
 

Último (20)

A brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProA brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision Pro
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptx
 
Secure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech LabsSecure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech Labs
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
priority interrupt computer organization
priority interrupt computer organizationpriority interrupt computer organization
priority interrupt computer organization
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
AntColonyOptimizationManetNetworkAODV.pptx
AntColonyOptimizationManetNetworkAODV.pptxAntColonyOptimizationManetNetworkAODV.pptx
AntColonyOptimizationManetNetworkAODV.pptx
 
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfModule-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
 
Novel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsNovel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending Actuators
 
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
 
Substation Automation SCADA and Gateway Solutions by BRH
Substation Automation SCADA and Gateway Solutions by BRHSubstation Automation SCADA and Gateway Solutions by BRH
Substation Automation SCADA and Gateway Solutions by BRH
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training
 

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