Exception Handling In Java
Yeshodha S
Exception
Yeshodha S
• In Java, Exception is an unwanted or unexpected event,
which occurs during the execution of a program, i.e. at
run time, that disrupts the normal flow of the program’s
instructions.
• Exceptions can be caught and handled by the program. When
an exception occurs within a method, it creates an object.
• This object is called the exception object.
• It contains information about the exception, such as the name
and description of the exception and the state of the program
when the exception occurred.
Yeshodha S
Major reasons why an exception Occurs
• Invalid user input
int age = Integer.parseInt("abc"); // NumberFormatException
• Device failure
Example: Printer not responding PrinterException.
→
• Loss of network connection
Example: IOException when server not reachable.
• Physical limitations (out-of-disk memory)
Example: OutOfMemoryError.
• Code errors
Example: NullPointerException when using an object that is not created.
• Opening an unavailable file
FileNotFoundException
Yeshodha S
Errors
• Errors represent irrecoverable conditions such as Java virtual
machine (JVM) running out of memory, memory leaks, stack
overflow errors, library incompatibility, infinite recursion, etc.
OutOfMemoryError – JVM has no space left to create new objects.
StackOverflowError – Too many method calls without stopping (infinite
recursion).
VirtualMachineError – Serious internal error in the JVM.
LinkageError – Problems with incompatible libraries or classes.
• Errors are usually beyond the control of the programmer, and we
should not try to handle errors.
Yeshodha S
Exception Hierarchy
• All exception and error types are subclasses of the
class Throwable, which is the base class of the hierarchy.
• Exception This class is used for exceptional conditions
that user programs should catch.
NullPointerException is an example of such an
exception.
• Error is 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.
Exception Hierarchy
Yeshodha S
Types of Exceptions
Yeshodha S
Yeshodha S
Exceptions can be categorized in two ways:
• Built-in Exceptions
• Checked Exception
• Unchecked Exception
• User-Defined Exceptions
Yeshodha S
Built-in Exceptions
Built-in exceptions are the exceptions that are available in
Java libraries. These exceptions are suitable to explain
certain error situations.
• Checked Exceptions: Checked exceptions are called
compile- time exceptions because these exceptions are
checked at compile-time by the compiler.
• Unchecked Exceptions: The unchecked exceptions are
just opposite to the checked exceptions. The compiler will
not check these exceptions at compile time. In simple
words, if a program throws an unchecked exception, and
even if we didn’t handle or declare it, the program would
not give a compilation error.
Yeshodha S
User-Defined Exceptions:
• Sometimes, the built-in exceptions in Java are not able to
describe a certain situation. In such cases, users can also
create exceptions, which are called ‘user-defined
Exceptions’.
Yeshodha S
How Does JVM Handle an Exception?
• Default Exception Handling: Whenever inside a method, if
an exception has occurred, the method creates an Object
known as an Exception Object and hands it off to
the run-time system(JVM).
• The exception object contains the name and description
of the exception and the current state of the program
where the exception has occurred.
• Creating the Exception Object and handling it in the run-
time system is called throwing an Exception.
Yeshodha S
How Programmer Handle an Exception?
• Customized Exception Handling: Java exception handling
is managed via five keywords: try, catch, throw,
throws, and finally.
Checked Exception
Yeshodha S
UnChecked Exception
Yeshodha S
Yeshodha S
Syntax of try-catch Block
try {
// Block of code to try
}
catch(ExceptionName obj) {
// Block of code to handle errors
}
Internal Working of Java try-catch block
Yeshodha S
Checked Exception
Yeshodha S
Unchecked Exception
Yeshodha S
Methods To Print Exceptions In Java
• 1. java.lang.Throwable.printStackTrace() method:
By using this method, we will get the
name(e.g., java.lang.ArithmeticException) and
description(e.g., / by zero) of an exception separated by a
colon, and the stack trace (wherein the code, that exception
has occurred) in the next line.
• 2. toString()method :
Using this method will only get the name and
description of an exception. Note that this method is
overridden in the Throwable class.
Yeshodha S
Yeshodha S
Methods To Print Exceptions In Java
3.java.lang.Throwable.getMessage() method:
Using this method, we will only get a description of an
exception.
Methods To Print Exceptions In Java
Yeshodha S
Yeshodha S
Finally Blocks
• 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 cleanup
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.
Finally Blocks
Try
{
// Block of code to try
}
catch(ExceptionName obj) {
// Block of code to
handle errors
}
Finally
{
// cleanup code
}
Yeshodha S
Finally Blocks
Yeshodha S
Yeshodha S
Java Multi-catch block
• A try block can be followed by one or more catch blocks.
• Each catch block must contain a different exception
handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch
block.
• At a time only one exception occurs and at a time only
one catch block is executed.
• All catch blocks must be ordered from most specific to
most general, i.e. catch for ArithmeticException must
come before catch for Exception.
Java Multi-catch block
Yeshodha S
Java Multi-catch block
Yeshodha S
Yeshodha S
Nested Try Block
• A try block can be nested within another try block.
• This structure is termed as Nested try block.
Whenever an exception is raised within a nested try block,
its exception is pushed to Stack.
• The exception propagates from child to parent try block
and so on.
Nested Try Block
Yeshodha S
Yeshodha S
Yeshodha S
Throw Keyword
• The Java throw keyword is used to throw an exception
explicitly.
• Java throw
• The throw keyword in Java is used to explicitly throw
an exception from a method or any block of code.
• We can throw either checked or unchecked exception.
The throw keyword is mainly used to throw custom
exceptions.
• We specify the exception object which is to be thrown.
The Exception has some message with it that provides
the error description. These exceptions may be related
to user inputs, server, etc.
Yeshodha S
Syntax:
• Throw new
throwable_subclass;
Throwing Exception(But not handling it)
Yeshodha S
Yeshodha S

Overview of Exception Handling in Java.pptx

  • 1.
    Exception Handling InJava Yeshodha S
  • 2.
    Exception Yeshodha S • InJava, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. • Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. • This object is called the exception object. • It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.
  • 3.
    Yeshodha S Major reasonswhy an exception Occurs • Invalid user input int age = Integer.parseInt("abc"); // NumberFormatException • Device failure Example: Printer not responding PrinterException. → • Loss of network connection Example: IOException when server not reachable. • Physical limitations (out-of-disk memory) Example: OutOfMemoryError. • Code errors Example: NullPointerException when using an object that is not created. • Opening an unavailable file FileNotFoundException
  • 4.
    Yeshodha S Errors • Errorsrepresent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. OutOfMemoryError – JVM has no space left to create new objects. StackOverflowError – Too many method calls without stopping (infinite recursion). VirtualMachineError – Serious internal error in the JVM. LinkageError – Problems with incompatible libraries or classes. • Errors are usually beyond the control of the programmer, and we should not try to handle errors.
  • 5.
    Yeshodha S Exception Hierarchy •All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. • Exception This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. • Error is 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.
  • 6.
  • 7.
  • 8.
    Yeshodha S Exceptions canbe categorized in two ways: • Built-in Exceptions • Checked Exception • Unchecked Exception • User-Defined Exceptions
  • 9.
    Yeshodha S Built-in Exceptions Built-inexceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. • Checked Exceptions: Checked exceptions are called compile- time exceptions because these exceptions are checked at compile-time by the compiler. • Unchecked Exceptions: The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare it, the program would not give a compilation error.
  • 10.
    Yeshodha S User-Defined Exceptions: •Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
  • 11.
    Yeshodha S How DoesJVM Handle an Exception? • Default Exception Handling: Whenever inside a method, if an exception has occurred, the method creates an Object known as an Exception Object and hands it off to the run-time system(JVM). • The exception object contains the name and description of the exception and the current state of the program where the exception has occurred. • Creating the Exception Object and handling it in the run- time system is called throwing an Exception.
  • 12.
    Yeshodha S How ProgrammerHandle an Exception? • Customized Exception Handling: Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
  • 13.
  • 14.
  • 15.
    Yeshodha S Syntax oftry-catch Block try { // Block of code to try } catch(ExceptionName obj) { // Block of code to handle errors }
  • 16.
    Internal Working ofJava try-catch block Yeshodha S
  • 17.
  • 18.
  • 19.
    Methods To PrintExceptions In Java • 1. java.lang.Throwable.printStackTrace() method: By using this method, we will get the name(e.g., java.lang.ArithmeticException) and description(e.g., / by zero) of an exception separated by a colon, and the stack trace (wherein the code, that exception has occurred) in the next line. • 2. toString()method : Using this method will only get the name and description of an exception. Note that this method is overridden in the Throwable class. Yeshodha S
  • 20.
    Yeshodha S Methods ToPrint Exceptions In Java 3.java.lang.Throwable.getMessage() method: Using this method, we will only get a description of an exception.
  • 21.
    Methods To PrintExceptions In Java Yeshodha S
  • 22.
    Yeshodha S Finally Blocks •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 cleanup 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.
  • 23.
    Finally Blocks Try { // Blockof code to try } catch(ExceptionName obj) { // Block of code to handle errors } Finally { // cleanup code } Yeshodha S
  • 24.
  • 25.
    Yeshodha S Java Multi-catchblock • A try block can be followed by one or more catch blocks. • Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. • At a time only one exception occurs and at a time only one catch block is executed. • All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • 26.
  • 27.
  • 28.
    Yeshodha S Nested TryBlock • A try block can be nested within another try block. • This structure is termed as Nested try block. Whenever an exception is raised within a nested try block, its exception is pushed to Stack. • The exception propagates from child to parent try block and so on.
  • 29.
  • 30.
  • 31.
    Yeshodha S Throw Keyword •The Java throw keyword is used to throw an exception explicitly. • Java throw • The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. • We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions. • We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.
  • 32.
    Yeshodha S Syntax: • Thrownew throwable_subclass;
  • 33.
    Throwing Exception(But nothandling it) Yeshodha S
  • 34.