SlideShare uma empresa Scribd logo
1 de 50
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.");
}
}
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.
• 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
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.
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
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
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.
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.
• 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
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 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.
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

Mais conteúdo relacionado

Mais procurados

Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

Mais procurados (20)

Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Basic Java I
Basic Java IBasic Java I
Basic Java I
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
CS3391 -OOP -UNIT – IV NOTES FINAL.pdfCS3391 -OOP -UNIT – IV NOTES FINAL.pdf
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 

Semelhante a Java-Unit 3- Chap2 exception handling

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
 

Semelhante a 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
 
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
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
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
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 

Mais de raksharao

Mais de raksharao (20)

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
 
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
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
 
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
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
 
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
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
FIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer LanguagesFIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer Languages
 

Último

+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
Health
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 

Último (20)

+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 

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."); } }
  • 15.
  • 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.
  • 17.
  • 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
  • 20.
  • 21.
  • 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.
  • 24.
  • 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
  • 27.
  • 28.
  • 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
  • 30.
  • 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.
  • 32.
  • 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.
  • 36.
  • 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
  • 38.
  • 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.
  • 43.
  • 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.
  • 45.
  • 46.
  • 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.