SlideShare una empresa de Scribd logo
1 de 29
EXCEPTION HANDLING IN JAVA
Elizabeth Alexander
Hindustan University
JAVA - EXCEPTIONS
● An exception (or exceptional event) is a problem that arises during the execution
of a program.
● When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore,
these exceptions are to be handled.
● An exception can occur for many different reasons. Following are some scenarios
where an exception occurs.
■ A user has entered an invalid data.
■ A file that needs to be opened cannot be found.
■ A network connection has been lost in the middle of communications or
the JVM has run out of memory.
● Some of these exceptions are caused by user error, others by programmer error,
and others by physical resources that have failed in some manner.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not try
to catch.
Exception: Exception indicates conditions that a reasonable application might try to
catch.
Exception Hierarchy
● All exception and errors types are subclasses of class Throwable, which is base
class of hierarchy.
● One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch. NullPointerException is an example of such an
exception.
● There is an important subclass of Exception, called RuntimeException.Exceptions
of this type are automatically defined for the programs that you write and include
things such as division by zero and invalid array indexing.
Exception Hierarchy
● Another branch,Error which defines exceptions that are not expected to be
caught under normal circumstances by your program ,
● Errors are used by the Java run-time system(JVM) to indicate errors having to do
with the run-time environment itself(JRE). StackOverflowError is an example of
such an error.
Types of Exceptions
● Java’s exceptions can be categorized into two types:
Checked exceptions
Unchecked exceptions
1. Checked exceptions −
● A checked exception is an exception that occurs at the compile time.
● These are also called as compile time exceptions.
● These exceptions cannot simply be ignored at the time of compilation, the
programmer should take care of (handle) these exceptions.
● checked exceptions are subject to the catch or specify a requirement, which
means they require catching or declaration. This requirement is optional for
unchecked exceptions.
● Code that uses a checked exception will not compile if the catch or specify
rule is not followed.
Types of Exceptions Cont...
● All Java exceptions are checked exceptions except those of the Error and
RuntimeException classes and their subclasses.
■ For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then a
FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
■ Since the methods read() and close() of FileReader class throws
IOException, you can observe that the compiler notifies to handle
IOException, along with FileNotFoundException.
Types of Exceptions Cont...
2. Unchecked exceptions − An unchecked exception is an exception that occurs at
the time of execution.
● These are also called as Runtime Exceptions.
● These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
● For example, if you have declared an array of size 5 in your program, and trying
to call the 6th element of the array then an
ArrayIndexOutOfBoundsExceptionexception occurs.
3. Errors − These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer.
● Errors are typically ignored in your code because you can rarely do anything
about an error.
● For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.
Exception Handling
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at
statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If
we perform exception handling, rest of the statement will be executed. That is why we
use exception handling in java.
How JVM handle an Exception?
Default Exception Handling : Whenever inside a method, if an exception has
occurred, the method creates an Object known as Exception Object and hands it off
to the run-time system(JVM).
● The exception object contains name and description of the exception, and current
state of the program where exception has occurred.
● Creating the Exception Object and handling it to the run-time system is called
throwing an Exception.
● There might be the list of the methods that had been called to get to the method
where exception was occurred. This ordered list of the methods is called Call
Stack.
● Now the following procedure will happen.
● The run-time system searches the call stack to find the method that contains
block of code that can handle the occurred exception. The block of the code is
called Exception handler.
Exception Handling
● The run-time system starts searching from the method in which exception
occurred, proceeds through call stack in the reverse order in which methods
were called.
● If it finds appropriate handler then it passes the occurred exception to it.
Appropriate handler means the type of the exception object thrown matches
the type of the exception object it can handle.
● If run-time system searches all the methods on call stack and couldn’t have
found the appropriate handler then run-time system handover the Exception
Object to default exception handler , which is part of run-time system. This
handler prints the exception information in the following format and terminates
program abnormally.
How Programmer handles an exception?
Customized Exception Handling :
● Java exception handling is managed via five keywords: try, catch, throw,
throws, and finally.
● Program statements that can raise exceptions are contained within a try block.
● If an exception occurs within the try block, it is thrown.
● System-generated exceptions are automatically thrown by the Java run-time
system. To manually throw an exception, use the keyword throw.
● Any exception that is thrown out of a method must be specified as such by a
throws clause.
● Any code that absolutely must be executed after a try block completes is put in a
finally block.
Advantage of Exception Handling
● Maintain the normal flow of the application.: Exception normally disrupts the
normal flow of the application that is why we use exception handling.
● Separating Error-Handling Code from "Regular" Code : Exceptions provide
the means to separate the details of what to do when something out of the
ordinary happens from the main logic of a program.
● Propagating Errors Up the Call Stack : Another advantage of exceptions is the
ability to propagate error reporting up the call stack of methods.
○ Suppose that the readFile method is the fourth method in a series of nested
method calls made by the main program: method1 calls method2, which calls
method3, which finally calls readFile.
○ Suppose also that method1 is the only method interested in the errors that
might occur within readFile.
Advantage of Exception Handling Cont...
○ The Java runtime environment searches backward through the call stack to
find any methods that are interested in handling a particular exception.
○ A method can duck any exceptions thrown within it, thereby allowing a
method farther up the call stack to catch it.
○ Hence, only the methods that care about errors have to worry about
detecting errors.
Grouping and Differentiating Error Types : Because all exceptions thrown within a
program are objects, the grouping or categorizing of exceptions is a natural outcome of
the class hierarchy.
● An example of a group of related exception classes in the Java platform are those
defined in java.io — IOException and its descendants.
● IOException is the most general and represents any type of error that can occur
when performing I/O. Its descendants represent more specific errors. For
example, FileNotFoundException means that a file could not be located on disk.
Try Catch in Java – Exception handling
Try block
● The try block contains set of statements where an exception can occur.
● A try block is always followed by a catch block, which handles the exception that
occurs in associated try block.
● A try block must be followed by catch blocks or finally block or both.
Syntax of try block
try{
//statements that may cause an exception
}
● While writing a program, if certain statements in a program can throw a exception,
enclosed them in try block and handle that exception
Try Catch in Java- Cont...
Catch block
● A catch block is where handle the exceptions are handled
● This block must follow the try block.
● A single try block can have several catch blocks associated with it.
● We can catch different exceptions in different catch blocks.
● When an exception occurs in try block, the corresponding catch block that
handles that particular exception executes.
● For example if an arithmetic exception occurs in try block then the statements
enclosed in catch block for arithmetic exception executes.
Try Catch in Java- Cont...
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Multiple catch blocks in Java
Rules about multiple catch blocks
● a single try block can have any number of catch blocks.
● A generic catch block can handle all the exceptions
catch(Exception e){
//This catch block catches all the exceptions
}
● If no exception occurs in try block then the catch blocks are completely ignored.
● Corresponding catch blocks execute for that specific type of exception:
■ catch(ArithmeticException e) is a catch block that can hanlde
ArithmeticException
■ catch(NullPointerException e) is a catch block that can handle
NullPointerException
● If an exception occurs in try block then the control of execution is passed to the
corresponding catch block.
● A single try block can have multiple catch blocks associated with it, you should
place the catch blocks in such a way that the generic exception handler catch
block is at the last
● The generic exception handler can handle all the exceptions but you should place
is at the end
● if you place it at the before all the catch blocks then it will display the generic
message. The user should get a meaningful message for each type of exception
rather than a generic message.
throws Keyword
● Throws keyword is used for handling checked exceptions
● It gives an information to the programmer that there may occur an exception so it
is better for the programmer to provide the exception handling code so that
normal flow can be maintained.
returntype methodname() throws exception_list
{
//method code
}
● Any method that is capable of causing exceptions must list all the exceptions
possible during its execution, so that anyone calling that method gets a prior
knowledge about which exceptions are to be handled. A method can do so by
using the throws keyword.
throw exception in java
● Throw keyword can also be used for throwing custom/user defined exceptions
● throw keyword is used to throw an exception explicitly.
● Only object of Throwable class or its sub classes can be thrown.
● Program execution stops on encountering throw statement, and the closest catch
statement is checked for matching type of exception.
Syntax :
■ throw ThrowableInstance
finally
● A finally keyword is used to create a block of code that follows a try block.
● A finally block of code is always executed whether an exception has occurred or
not. Using a finally block, it lets you run any clean-up type statements that you
want to execute, no matter what happens in the protected code.
● A finally block appears at the end of catch block.
User defined exception in java
● In java we can create our own exception class and throw that exception using
throw keyword. These exceptions are known as user-defined or custom
exceptions.
Syntax
● class classname extends Exception
Notes:
■ 1. User-defined exception must extend Exception class.
■ 2. The exception is thrown using throw keyword.

Más contenido relacionado

La actualidad más candente

Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 

La actualidad más candente (20)

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-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
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java interface
Java interfaceJava interface
Java interface
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java exception
Java exception Java exception
Java exception
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 

Similar a Exception handling in java

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
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
Deepak Sharma
 

Similar a Exception handling in java (20)

Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and 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
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Exception handling
Exception handlingException handling
Exception handling
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.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
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
 
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 prograaming
EXCEPTION HANDLING in prograamingEXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograaming
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
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
Exception handlingException handling
Exception handling
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – III  NOTES FINAL.pdfCS3391 -OOP -UNIT – III  NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 

Más de Elizabeth alexander (11)

Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Java applet
Java appletJava applet
Java applet
 
Io streams
Io streamsIo streams
Io streams
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Quantitative Aptitude- Number System
Quantitative Aptitude- Number SystemQuantitative Aptitude- Number System
Quantitative Aptitude- Number System
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 

Último

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Último (20)

Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
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
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
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...
 
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
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
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
 

Exception handling in java

  • 1. EXCEPTION HANDLING IN JAVA Elizabeth Alexander Hindustan University
  • 2. JAVA - EXCEPTIONS ● An exception (or exceptional event) is a problem that arises during the execution of a program. ● When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. ● An exception can occur for many different reasons. Following are some scenarios where an exception occurs. ■ A user has entered an invalid data. ■ A file that needs to be opened cannot be found. ■ A network connection has been lost in the middle of communications or the JVM has run out of memory. ● Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
  • 3. Error vs Exception Error: An Error indicates serious problem that a reasonable application should not try to catch. Exception: Exception indicates conditions that a reasonable application might try to catch. Exception Hierarchy ● All exception and errors types are subclasses of class Throwable, which is base class of hierarchy. ● One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. ● There is an important subclass of Exception, called RuntimeException.Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.
  • 4. Exception Hierarchy ● Another branch,Error which defines exceptions that are not expected to be caught under normal circumstances by your program , ● Errors are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
  • 5.
  • 6.
  • 7.
  • 8. Types of Exceptions ● Java’s exceptions can be categorized into two types: Checked exceptions Unchecked exceptions 1. Checked exceptions − ● A checked exception is an exception that occurs at the compile time. ● These are also called as compile time exceptions. ● These exceptions cannot simply be ignored at the time of compilation, the programmer should take care of (handle) these exceptions. ● checked exceptions are subject to the catch or specify a requirement, which means they require catching or declaration. This requirement is optional for unchecked exceptions. ● Code that uses a checked exception will not compile if the catch or specify rule is not followed.
  • 9. Types of Exceptions Cont... ● All Java exceptions are checked exceptions except those of the Error and RuntimeException classes and their subclasses. ■ For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. ■ Since the methods read() and close() of FileReader class throws IOException, you can observe that the compiler notifies to handle IOException, along with FileNotFoundException.
  • 10. Types of Exceptions Cont... 2. Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. ● These are also called as Runtime Exceptions. ● These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. ● For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs. 3. Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. ● Errors are typically ignored in your code because you can rarely do anything about an error. ● For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
  • 11. Exception Handling 1. statement 1; 2. statement 2; 3. statement 3; 4. statement 4; 5. statement 5;//exception occurs 6. statement 6; 7. statement 7; 8. statement 8; 9. statement 9; 10. statement 10; Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.
  • 12. How JVM handle an Exception? Default Exception Handling : Whenever inside a method, if an exception has occurred, the method creates an Object known as Exception Object and hands it off to the run-time system(JVM). ● The exception object contains name and description of the exception, and current state of the program where exception has occurred. ● Creating the Exception Object and handling it to the run-time system is called throwing an Exception. ● There might be the list of the methods that had been called to get to the method where exception was occurred. This ordered list of the methods is called Call Stack. ● Now the following procedure will happen. ● The run-time system searches the call stack to find the method that contains block of code that can handle the occurred exception. The block of the code is called Exception handler.
  • 13. Exception Handling ● The run-time system starts searching from the method in which exception occurred, proceeds through call stack in the reverse order in which methods were called. ● If it finds appropriate handler then it passes the occurred exception to it. Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle. ● If run-time system searches all the methods on call stack and couldn’t have found the appropriate handler then run-time system handover the Exception Object to default exception handler , which is part of run-time system. This handler prints the exception information in the following format and terminates program abnormally.
  • 14.
  • 15. How Programmer handles an exception? Customized Exception Handling : ● Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. ● Program statements that can raise exceptions are contained within a try block. ● If an exception occurs within the try block, it is thrown. ● System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. ● Any exception that is thrown out of a method must be specified as such by a throws clause. ● Any code that absolutely must be executed after a try block completes is put in a finally block.
  • 16. Advantage of Exception Handling ● Maintain the normal flow of the application.: Exception normally disrupts the normal flow of the application that is why we use exception handling. ● Separating Error-Handling Code from "Regular" Code : Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. ● Propagating Errors Up the Call Stack : Another advantage of exceptions is the ability to propagate error reporting up the call stack of methods. ○ Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program: method1 calls method2, which calls method3, which finally calls readFile. ○ Suppose also that method1 is the only method interested in the errors that might occur within readFile.
  • 17. Advantage of Exception Handling Cont... ○ The Java runtime environment searches backward through the call stack to find any methods that are interested in handling a particular exception. ○ A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it. ○ Hence, only the methods that care about errors have to worry about detecting errors. Grouping and Differentiating Error Types : Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy.
  • 18. ● An example of a group of related exception classes in the Java platform are those defined in java.io — IOException and its descendants. ● IOException is the most general and represents any type of error that can occur when performing I/O. Its descendants represent more specific errors. For example, FileNotFoundException means that a file could not be located on disk.
  • 19. Try Catch in Java – Exception handling Try block ● The try block contains set of statements where an exception can occur. ● A try block is always followed by a catch block, which handles the exception that occurs in associated try block. ● A try block must be followed by catch blocks or finally block or both. Syntax of try block try{ //statements that may cause an exception } ● While writing a program, if certain statements in a program can throw a exception, enclosed them in try block and handle that exception
  • 20. Try Catch in Java- Cont... Catch block ● A catch block is where handle the exceptions are handled ● This block must follow the try block. ● A single try block can have several catch blocks associated with it. ● We can catch different exceptions in different catch blocks. ● When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. ● For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
  • 21. Try Catch in Java- Cont... Syntax of try catch in java try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code }
  • 22. Multiple catch blocks in Java Rules about multiple catch blocks ● a single try block can have any number of catch blocks. ● A generic catch block can handle all the exceptions catch(Exception e){ //This catch block catches all the exceptions } ● If no exception occurs in try block then the catch blocks are completely ignored. ● Corresponding catch blocks execute for that specific type of exception: ■ catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException ■ catch(NullPointerException e) is a catch block that can handle NullPointerException
  • 23. ● If an exception occurs in try block then the control of execution is passed to the corresponding catch block. ● A single try block can have multiple catch blocks associated with it, you should place the catch blocks in such a way that the generic exception handler catch block is at the last ● The generic exception handler can handle all the exceptions but you should place is at the end ● if you place it at the before all the catch blocks then it will display the generic message. The user should get a meaningful message for each type of exception rather than a generic message.
  • 24. throws Keyword ● Throws keyword is used for handling checked exceptions ● It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. returntype methodname() throws exception_list { //method code } ● Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. A method can do so by using the throws keyword.
  • 25. throw exception in java ● Throw keyword can also be used for throwing custom/user defined exceptions ● throw keyword is used to throw an exception explicitly. ● Only object of Throwable class or its sub classes can be thrown. ● Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. Syntax : ■ throw ThrowableInstance
  • 26.
  • 27. finally ● A finally keyword is used to create a block of code that follows a try block. ● A finally block of code is always executed whether an exception has occurred or not. Using a finally block, it lets you run any clean-up type statements that you want to execute, no matter what happens in the protected code. ● A finally block appears at the end of catch block.
  • 28.
  • 29. User defined exception in java ● In java we can create our own exception class and throw that exception using throw keyword. These exceptions are known as user-defined or custom exceptions. Syntax ● class classname extends Exception Notes: ■ 1. User-defined exception must extend Exception class. ■ 2. The exception is thrown using throw keyword.