SlideShare a Scribd company logo
Chapter2-Exception Handling
Unit 3
contents
• The exception hierarchy
• Exception handling fundamentals
• Try and catch
• The consequences of an uncaught exception
• Using multiple catch statements
• Catching subclass exceptions
• Nested try blocks
• Throwing an exception
• Re-throwing an exception
• Using finally
• Using throws
• Java’s built-in exception
• Creating exception subclasses
introduction
• A exception is an error that occurs at run time.
• An advantage of exception handling is that it automates
much of error handling code that previously had to
entered “by hand” into large program.
• Exception handling streamlines error handling by
allowing your program to define a block of code called an
exception handler, I.e. executed automatically when an
error occurs.
• It is not necessary to manually check the success or
failure of each specific operation or method call.
• If an error occurs, it will be processed by the exception
handler.
• Another reason that exception handling is important is
that java standard exceptions for common program
errors, such as divide-by-zero or file or not found.
• To respond to these errors , your programs must watch
for and handle these exceptions.
• To be a successful Java programmer means that you are
fully capable of navigating Java’s exception handling
subsystem.
The Exception Hierarchy
• In Java, all exceptions are represented by classes.
• All exception classes are derived from a class called
Throwable.
• When an exception occurs in a program, an object of
some type of exception class is generated.
• There are two direct subclasses of Throwable:
Exception and Error
• Exceptions of the type Error are related to the errors that
occur in Java Virtual machine itself and not in your
program.
• These exceptions are usually beyond your control, your
program will not usually deal with them.
• Errors that result from program activity are represented
by subclasses of Exceptions.
• For example: divide- by-zero , array boundary , file
errors fall into this category.
• An important subclass of Exception is
RuntimeException , which is used to represent
various common types of run-time errors.
Exception handling fundamentals
• Java Exception handling has five keywords:
▫ try
▫ catch
▫ throw
▫ Throws
▫ finally
• Program statements that you want to monitor for
exceptions are contained within a try block.
• If an exception occurs within the try block , it is thrown
• Your code can catch this using a catch block and handle
them it in some rational manner.
• System generated exceptions are automatically thrown
by Java runtime system.
• To manually throw the exceptions, use the keyword
throw.
• In some case, an exception that is thrown out of the
method must be specified as such by a throws clause.
• Any code that absolutely must be executed upon exiting
from a try block is put in a finally block.
Using try and catch
• These keywords work together;
• you can’t have a try without a catch, or catch
without a try
try {
// block of code to monitor for errors
}
catch (ExcepType1 exOb) {
// handler for ExcepType1
}
catch (ExcepType2 exOb) {
// handler for ExcepType2
}...
• Here, ExcepType is the type of exception that has
occurred.
• When an exception is thrown, it is caught by its
corresponding catch statement, which then processes the
exception.
• As the general form shows, there can be more than
one catch statement associated with a try.
• The type of the exception determines which catch
statement is executed.
• When an exception is caught, exOb will receive its value.
• Here is an important point: If no exception is thrown,
then a try block ends normally, and all of its catch
statements are bypassed. Execution resumes
with the first statement following the last catch.
• Thus, catch statements are executed only if an
exception is thrown.
A simple exception example
• An error to attempt to index an array beyond its boundaries.
• When this occurs, the JVM throws an
ArrayIndexOutOfBoundsException.
• This program displays the following output:
Before exception is generated.
Index out-of-bounds!
After catch statement.
• the code that you want to monitor for errors is
contained within a try block.
• when an exception occurs the exception is thrown out of
the try block and caught by the catch statement.
• After the catch statement executes, program
control continues with the statements following the
catch.
• it is the job of your exception handler to remedy the
problem that caused the exception so that program
execution can continue normally.
• if no exception is thrown by a try block, no catch
statements will be executed and program control
resumes after the catch statement
The consequences of an Uncaught
Exception
• By having an exception handler, it prevents abnormal
program termination.
• If your program does not catch an exception, then it will
be caught by the JVM.
• JVM exception handler terminates the execution and
displays a stack trace and error message.
// This won't work!
class ExcTypeMismatch {
public static void main(String args[]) {
int nums[] = new int[4];
try {
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 10;
System.out.println("this won't be displayed");
}
/* Can't catch an array boundary error with an
ArithmeticException. */
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Index out-of-bounds!");
}
System.out.println("After catch statement.");
}
}
Java-Unit 3- Chap2 exception handling
Exceptions enable you to handle errors
gracefully
• By having an exception handler ,it enables your program
to respond to an error and then continue running.
• If a division by zero occurs, an ArithmeticException
is generated.
• In the following program, this exception us handled by
reporting the error then continuing with the execution.
• Thus attempting to divide by zero does not cause an
abrupt run-time error resulting a termination of the
program.
Java-Unit 3- Chap2 exception handling
• Makes another important point, once an exception has
been handled, it is removed for the system.
• In program , each pass through the loop enters the try
block new, any prior exception have been handled.
• This enables your program to handle repeated errors.
Using multiple catch statements
• We can associate more than one catch statement with a
try.
• Each catch must catch a different type of exception.
• Program that catch both array boundary and divide by
zero errors
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
Catching subclass exceptions
• A catch clause for a superclass will also match any of its
subclasses.
• Superclass of all exceptions is Throwable , to catch all
possible exceptions.
• If you want to catch exceptions of both superclass type
and a subclass type put the subclass first in the catch
sequence.
• If you don’t then the superclass catch will also catch all
derived classes.
• Putting the super class first causes unreachable code to
be created, since the subclass catch clause can never
execute.
• In java, unreachable code is an error.
Java-Unit 3- Chap2 exception handling
output
Nested Try blocks
• One try block can be nested within another.
• An exception generated within inner try block that is not
caught by the catch block associated with the try
propagated to the outer try block
• Ex: ArrayIndecOutOfBoundException is not caught by
the inner catch , but the outer catch
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
Throwing an exception
• It is possible to throw an exception by using throw
statement.
• General statement is:
▫ throw exceptObj;
• Here the exceptObj should be an object of exception
class derived from Throwable.
• An example that illustrates the throw statement by
manually throwing an ArithmeticException
Java-Unit 3- Chap2 exception handling
Rethrowing an exception
• An exception caught by one catch statement can be
rethrown so that it can be caught by an outer catch.
• It allows multiple handlers access to the exception.
• When you rethrow an exception, it will not be recaught
by the same catch statement.
• It will propagate to the next catch statement.
Java-Unit 3- Chap2 exception handling
class RethrowDemo {
public static void main(String args[]) {
try {
Rethrow.genException();
}
catch(ArrayIndexOutOfBoundsException exc) {
// recatch exception
System.out.println("Fatal error – " +
"program terminated.");
}
}
}
Closer look at Throwable class
Using finally
• When you want to define a block of code that will execute
when a try/catch block is left.
• A method that has opened a file or a network connection
that needs to be closed.
• To specify a block of code to execute when a try/catch
block is exited, included a finally block at the end of
try/catch sequence.
• General form of try/catch that includes finally is as
shown below.
Java-Unit 3- Chap2 exception handling
• The finally block will be executed whenever execution
leaves a try/catch block, no matter what condition causes
it.
• i.e. whether try block ends normally or because of an
exception, last code that will be executed is defined by
finally.
• Example of using the concept of finally
Java-Unit 3- Chap2 exception handling
class FinallyDemo {
public static void main(String args[]) {
for(int i=0; i < 3; i++) {
UseFinally.genException(i);
System.out.println();
}
}
}
• Here is the output produced by the program.
Receiving 0
Can't divide by Zero!
Leaving try.
Receiving 1
No matching element found.
Leaving try.
Receiving 2
Leaving try.
Using throws
• If a method generates an exception that it does not
handle, it must declare that exception in throws clause.
ret_type methname(param_list) throws excp_list{
//body
}
▫ here excp_list is a comma sepearted list of exceptions
that the method might throw outside of itself.
▫ When performing keyboard input, you should add the
clause
 throws java.IOException
• An example that handles IOException.
• It creates a method called prompt(), which displays a
prompting message and then reads a character from the
keyboard.
• Since the input is being performed , an IOException
might occur.
• prompt() uses a throws() which means that the calling
method must handle it.
• The following example, the calling method is main(), and
deals with the error.
Java-Unit 3- Chap2 exception handling
Java built-in exceptions
• Inside standard package java.lang , Java defines several
exception classes.
• There are two kinds of exceptions
• Checked exceptions
▫ The exceptions defined by java.lang that must be
included in a methods throws list if that method can
generate one of these exceptions and does not handle
it itself.
• Unchecked exceptions
▫ if the compiler does not check to see if a method
handles or throws these exceptions.
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
Creating Exception subclasses
• Creating an exception is easy
• Just define a subclass of exception class.
• This subclass need not implement anything, it inherits
those methods provided by Throwable class.
• Exception called NonIntResultException , which is
generated when the result of dividing two integer values
produce a result with a fractional and override of the
toString() method, allowing the description to be printed
using println() method.
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
Ad

More Related Content

What's hot (20)

Problemas Resuelto De Corriente Continua.1
Problemas Resuelto De Corriente Continua.1Problemas Resuelto De Corriente Continua.1
Problemas Resuelto De Corriente Continua.1
julio ulacio
 
Electromagnetismo-Fisica II
Electromagnetismo-Fisica IIElectromagnetismo-Fisica II
Electromagnetismo-Fisica II
shanirarc
 
Problemas resueltos capitulo 23 fisica-serway
Problemas resueltos capitulo 23 fisica-serwayProblemas resueltos capitulo 23 fisica-serway
Problemas resueltos capitulo 23 fisica-serway
Victor Gutierrez
 
Circuitos polifasicos parte 2
Circuitos polifasicos parte 2Circuitos polifasicos parte 2
Circuitos polifasicos parte 2
Israel Magaña
 
leyes de coulomb y campo electrico
leyes de coulomb y campo electricoleyes de coulomb y campo electrico
leyes de coulomb y campo electrico
Carlos Daniel Campoverde Pillajo
 
Electrónica digital: Comparadores
Electrónica digital: ComparadoresElectrónica digital: Comparadores
Electrónica digital: Comparadores
SANTIAGO PABLO ALBERTO
 
5. Problemas de campo eléctrico
5. Problemas de campo eléctrico5. Problemas de campo eléctrico
5. Problemas de campo eléctrico
Álvaro Pascual Sanz
 
Informe01
Informe01Informe01
Informe01
Hola Carlos
 
Informe campo magnetico
Informe campo magneticoInforme campo magnetico
Informe campo magnetico
AngelaBarajasM
 
Electrostatica y electromagnetismo
Electrostatica y electromagnetismoElectrostatica y electromagnetismo
Electrostatica y electromagnetismo
DAVIDADAMSBARRENECHE
 
Fuerza electrica 1
Fuerza electrica 1Fuerza electrica 1
Fuerza electrica 1
Viter Becerra
 
SISTEMA TETRAGONAL.pptx
SISTEMA TETRAGONAL.pptxSISTEMA TETRAGONAL.pptx
SISTEMA TETRAGONAL.pptx
EikerFalcon1
 
Carga eléctrica, física II
Carga eléctrica, física IICarga eléctrica, física II
Carga eléctrica, física II
leticiazabalveytia
 
Sd2
Sd2Sd2
Sd2
Velmuz Buzz
 
electricidad y magnetismo ejercicios resueltos Capitulo 5
electricidad y magnetismo  ejercicios resueltos  Capitulo 5electricidad y magnetismo  ejercicios resueltos  Capitulo 5
electricidad y magnetismo ejercicios resueltos Capitulo 5
J Alexander A Cabrera
 
6 - circuito Paralelo.pdf
6 - circuito Paralelo.pdf6 - circuito Paralelo.pdf
6 - circuito Paralelo.pdf
PaulaGarcavalero
 
Polarización por divisor de voltaje
Polarización por divisor de voltajePolarización por divisor de voltaje
Polarización por divisor de voltaje
Oscar Mendoza Gutiérrez
 
Divissor de voltaje y corriente
Divissor de voltaje y corriente Divissor de voltaje y corriente
Divissor de voltaje y corriente
karmerc
 
Mallas y nodos
Mallas y nodosMallas y nodos
Mallas y nodos
amerika_09
 
Energía eléctrica
Energía eléctricaEnergía eléctrica
Energía eléctrica
aureortemen
 
Problemas Resuelto De Corriente Continua.1
Problemas Resuelto De Corriente Continua.1Problemas Resuelto De Corriente Continua.1
Problemas Resuelto De Corriente Continua.1
julio ulacio
 
Electromagnetismo-Fisica II
Electromagnetismo-Fisica IIElectromagnetismo-Fisica II
Electromagnetismo-Fisica II
shanirarc
 
Problemas resueltos capitulo 23 fisica-serway
Problemas resueltos capitulo 23 fisica-serwayProblemas resueltos capitulo 23 fisica-serway
Problemas resueltos capitulo 23 fisica-serway
Victor Gutierrez
 
Circuitos polifasicos parte 2
Circuitos polifasicos parte 2Circuitos polifasicos parte 2
Circuitos polifasicos parte 2
Israel Magaña
 
Informe campo magnetico
Informe campo magneticoInforme campo magnetico
Informe campo magnetico
AngelaBarajasM
 
Electrostatica y electromagnetismo
Electrostatica y electromagnetismoElectrostatica y electromagnetismo
Electrostatica y electromagnetismo
DAVIDADAMSBARRENECHE
 
SISTEMA TETRAGONAL.pptx
SISTEMA TETRAGONAL.pptxSISTEMA TETRAGONAL.pptx
SISTEMA TETRAGONAL.pptx
EikerFalcon1
 
electricidad y magnetismo ejercicios resueltos Capitulo 5
electricidad y magnetismo  ejercicios resueltos  Capitulo 5electricidad y magnetismo  ejercicios resueltos  Capitulo 5
electricidad y magnetismo ejercicios resueltos Capitulo 5
J Alexander A Cabrera
 
Divissor de voltaje y corriente
Divissor de voltaje y corriente Divissor de voltaje y corriente
Divissor de voltaje y corriente
karmerc
 
Mallas y nodos
Mallas y nodosMallas y nodos
Mallas y nodos
amerika_09
 
Energía eléctrica
Energía eléctricaEnergía eléctrica
Energía eléctrica
aureortemen
 

Similar to Java-Unit 3- Chap2 exception handling (20)

Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
ARUNPRANESHS
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
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
HayomeTakele
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil Mehmoood
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
Ravindra Rathore
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptxusing Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
Rajkattamuri
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Young Alista
 
Exception
ExceptionException
Exception
James Wong
 
Exception
ExceptionException
Exception
Luis Goldster
 
Exception
ExceptionException
Exception
Harry Potter
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Tony Nguyen
 
Exception
ExceptionException
Exception
Tony Nguyen
 
Exception
ExceptionException
Exception
Hoang Nguyen
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
ARUNPRANESHS
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
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
HayomeTakele
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil Mehmoood
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptxusing Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
Rajkattamuri
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Ad

More from raksharao (20)

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
raksharao
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
raksharao
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
raksharao
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
raksharao
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
raksharao
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
raksharao
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
raksharao
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
raksharao
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
raksharao
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
raksharao
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
raksharao
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
raksharao
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
raksharao
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
raksharao
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
raksharao
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
raksharao
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
raksharao
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
FIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer LanguagesFIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer Languages
raksharao
 
Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
raksharao
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
raksharao
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
raksharao
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
raksharao
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
raksharao
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
raksharao
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
raksharao
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
raksharao
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
raksharao
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
raksharao
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
raksharao
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
raksharao
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
raksharao
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
raksharao
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
raksharao
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
raksharao
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
raksharao
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
FIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer LanguagesFIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer Languages
raksharao
 
Ad

Recently uploaded (20)

RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 

Java-Unit 3- Chap2 exception handling

  • 2. contents • The exception hierarchy • Exception handling fundamentals • Try and catch • The consequences of an uncaught exception • Using multiple catch statements • Catching subclass exceptions • Nested try blocks • Throwing an exception • Re-throwing an exception • Using finally • Using throws • Java’s built-in exception • Creating exception subclasses
  • 3. introduction • A exception is an error that occurs at run time. • An advantage of exception handling is that it automates much of error handling code that previously had to entered “by hand” into large program. • Exception handling streamlines error handling by allowing your program to define a block of code called an exception handler, I.e. executed automatically when an error occurs. • It is not necessary to manually check the success or failure of each specific operation or method call. • If an error occurs, it will be processed by the exception handler.
  • 4. • Another reason that exception handling is important is that java standard exceptions for common program errors, such as divide-by-zero or file or not found. • To respond to these errors , your programs must watch for and handle these exceptions. • To be a successful Java programmer means that you are fully capable of navigating Java’s exception handling subsystem.
  • 5. The Exception Hierarchy • In Java, all exceptions are represented by classes. • All exception classes are derived from a class called Throwable. • When an exception occurs in a program, an object of some type of exception class is generated. • There are two direct subclasses of Throwable: Exception and Error • Exceptions of the type Error are related to the errors that occur in Java Virtual machine itself and not in your program. • These exceptions are usually beyond your control, your program will not usually deal with them.
  • 6. • Errors that result from program activity are represented by subclasses of Exceptions. • For example: divide- by-zero , array boundary , file errors fall into this category. • An important subclass of Exception is RuntimeException , which is used to represent various common types of run-time errors.
  • 7. Exception handling fundamentals • Java Exception handling has five keywords: ▫ try ▫ catch ▫ throw ▫ Throws ▫ finally • Program statements that you want to monitor for exceptions are contained within a try block. • If an exception occurs within the try block , it is thrown
  • 8. • Your code can catch this using a catch block and handle them it in some rational manner. • System generated exceptions are automatically thrown by Java runtime system. • To manually throw the exceptions, use the keyword throw. • In some case, an exception that is thrown out of the method must be specified as such by a throws clause. • Any code that absolutely must be executed upon exiting from a try block is put in a finally block.
  • 9. Using try and catch • These keywords work together; • you can’t have a try without a catch, or catch without a try try { // block of code to monitor for errors } catch (ExcepType1 exOb) { // handler for ExcepType1 } catch (ExcepType2 exOb) { // handler for ExcepType2 }...
  • 10. • Here, ExcepType is the type of exception that has occurred. • When an exception is thrown, it is caught by its corresponding catch statement, which then processes the exception. • As the general form shows, there can be more than one catch statement associated with a try. • The type of the exception determines which catch statement is executed. • When an exception is caught, exOb will receive its value. • Here is an important point: If no exception is thrown, then a try block ends normally, and all of its catch statements are bypassed. Execution resumes with the first statement following the last catch. • Thus, catch statements are executed only if an exception is thrown.
  • 11. A simple exception example • An error to attempt to index an array beyond its boundaries. • When this occurs, the JVM throws an ArrayIndexOutOfBoundsException.
  • 12. • This program displays the following output: Before exception is generated. Index out-of-bounds! After catch statement. • the code that you want to monitor for errors is contained within a try block. • when an exception occurs the exception is thrown out of the try block and caught by the catch statement. • After the catch statement executes, program control continues with the statements following the catch. • it is the job of your exception handler to remedy the problem that caused the exception so that program execution can continue normally. • if no exception is thrown by a try block, no catch statements will be executed and program control resumes after the catch statement
  • 13. The consequences of an Uncaught Exception • By having an exception handler, it prevents abnormal program termination. • If your program does not catch an exception, then it will be caught by the JVM. • JVM exception handler terminates the execution and displays a stack trace and error message.
  • 14. // This won't work! class ExcTypeMismatch { public static void main(String args[]) { int nums[] = new int[4]; try { System.out.println("Before exception is generated."); // generate an index out-of-bounds exception nums[7] = 10; System.out.println("this won't be displayed"); } /* Can't catch an array boundary error with an ArithmeticException. */ catch (ArithmeticException exc) { // catch the exception System.out.println("Index out-of-bounds!"); } System.out.println("After catch statement."); } }
  • 16. Exceptions enable you to handle errors gracefully • By having an exception handler ,it enables your program to respond to an error and then continue running. • If a division by zero occurs, an ArithmeticException is generated. • In the following program, this exception us handled by reporting the error then continuing with the execution. • Thus attempting to divide by zero does not cause an abrupt run-time error resulting a termination of the program.
  • 18. • Makes another important point, once an exception has been handled, it is removed for the system. • In program , each pass through the loop enters the try block new, any prior exception have been handled. • This enables your program to handle repeated errors.
  • 19. Using multiple catch statements • We can associate more than one catch statement with a try. • Each catch must catch a different type of exception. • Program that catch both array boundary and divide by zero errors
  • 22. Catching subclass exceptions • A catch clause for a superclass will also match any of its subclasses. • Superclass of all exceptions is Throwable , to catch all possible exceptions. • If you want to catch exceptions of both superclass type and a subclass type put the subclass first in the catch sequence. • If you don’t then the superclass catch will also catch all derived classes.
  • 23. • Putting the super class first causes unreachable code to be created, since the subclass catch clause can never execute. • In java, unreachable code is an error.
  • 26. Nested Try blocks • One try block can be nested within another. • An exception generated within inner try block that is not caught by the catch block associated with the try propagated to the outer try block • Ex: ArrayIndecOutOfBoundException is not caught by the inner catch , but the outer catch
  • 29. Throwing an exception • It is possible to throw an exception by using throw statement. • General statement is: ▫ throw exceptObj; • Here the exceptObj should be an object of exception class derived from Throwable. • An example that illustrates the throw statement by manually throwing an ArithmeticException
  • 31. Rethrowing an exception • An exception caught by one catch statement can be rethrown so that it can be caught by an outer catch. • It allows multiple handlers access to the exception. • When you rethrow an exception, it will not be recaught by the same catch statement. • It will propagate to the next catch statement.
  • 33. class RethrowDemo { public static void main(String args[]) { try { Rethrow.genException(); } catch(ArrayIndexOutOfBoundsException exc) { // recatch exception System.out.println("Fatal error – " + "program terminated."); } } }
  • 34. Closer look at Throwable class
  • 35. Using finally • When you want to define a block of code that will execute when a try/catch block is left. • A method that has opened a file or a network connection that needs to be closed. • To specify a block of code to execute when a try/catch block is exited, included a finally block at the end of try/catch sequence. • General form of try/catch that includes finally is as shown below.
  • 37. • The finally block will be executed whenever execution leaves a try/catch block, no matter what condition causes it. • i.e. whether try block ends normally or because of an exception, last code that will be executed is defined by finally. • Example of using the concept of finally
  • 39. class FinallyDemo { public static void main(String args[]) { for(int i=0; i < 3; i++) { UseFinally.genException(i); System.out.println(); } } }
  • 40. • Here is the output produced by the program. Receiving 0 Can't divide by Zero! Leaving try. Receiving 1 No matching element found. Leaving try. Receiving 2 Leaving try.
  • 41. Using throws • If a method generates an exception that it does not handle, it must declare that exception in throws clause. ret_type methname(param_list) throws excp_list{ //body } ▫ here excp_list is a comma sepearted list of exceptions that the method might throw outside of itself. ▫ When performing keyboard input, you should add the clause  throws java.IOException
  • 42. • An example that handles IOException. • It creates a method called prompt(), which displays a prompting message and then reads a character from the keyboard. • Since the input is being performed , an IOException might occur. • prompt() uses a throws() which means that the calling method must handle it. • The following example, the calling method is main(), and deals with the error.
  • 44. Java built-in exceptions • Inside standard package java.lang , Java defines several exception classes. • There are two kinds of exceptions • Checked exceptions ▫ The exceptions defined by java.lang that must be included in a methods throws list if that method can generate one of these exceptions and does not handle it itself. • Unchecked exceptions ▫ if the compiler does not check to see if a method handles or throws these exceptions.
  • 47. Creating Exception subclasses • Creating an exception is easy • Just define a subclass of exception class. • This subclass need not implement anything, it inherits those methods provided by Throwable class. • Exception called NonIntResultException , which is generated when the result of dividing two integer values produce a result with a fractional and override of the toString() method, allowing the description to be printed using println() method.