0% found this document useful (0 votes)
25 views

Exception Handling Unit 3

Exception Handling in Java allows handling of runtime errors so the application's flow is preserved. Exceptions can be caught and handled. Major reasons for exceptions include invalid user input, device failures, code errors, and unavailable files. Errors represent irrecoverable conditions like out of memory and are usually beyond a programmer's control.

Uploaded by

hiramanbhonde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Exception Handling Unit 3

Exception Handling in Java allows handling of runtime errors so the application's flow is preserved. Exceptions can be caught and handled. Major reasons for exceptions include invalid user input, device failures, code errors, and unavailable files. Errors represent irrecoverable conditions like out of memory and are usually beyond a programmer's control.

Uploaded by

hiramanbhonde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Exception Handling in Java is one of the effective means to handle runtime

errors so that the regular flow of the application can be preserved. Java Exception
Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
What are Java Exceptions?
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.
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are usually beyond the control of the
programmer, and we should not try to handle errors.
Difference between Error and Exception
Let us discuss the most important part which is the differences between Error
and Exception that is as follows:

• Error: An Error indicates a 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 error types are subclasses of the class Throwable, which is
the base class of the 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. Another
branch, 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.
Java Exception Hierarchy

Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries.
Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
• Checked Exception
• Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
1. 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.

2. 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’.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Methods to print the Exception information:
1. printStackTrace()
This method prints exception information in the format of the Name of the
exception: description of the exception, stack trace.
Example:
• Java

//program to print the exception information using printStackTrace() method

import java.io.*;

class GFG {

public static void main (String[] args) {

int a=5;

int b=0;

try{

System.out.println(a/b);

catch(ArithmeticException e){

e.printStackTrace();
}

Output
java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
2. toString()
The toString() method prints exception information in the format of the Name of
the exception: description of the exception.
Example:
• Java

//program to print the exception information using toString() method

import java.io.*;

class GFG1 {

public static void main (String[] args) {

int a=5;

int b=0;

try{

System.out.println(a/b);

}
catch(ArithmeticException e){

System.out.println(e.toString());

Output
java.lang.ArithmeticException: / by zero
3. getMessage()
The getMessage() method prints only the description of the exception.
Example:
• Java

//program to print the exception information using getMessage() method

import java.io.*;

class GFG1 {

public static void main (String[] args) {

int a=5;

int b=0;

try{

System.out.println(a/b);
}

catch(ArithmeticException e){

System.out.println(e.getMessage());

Output
/ by zero

What is try () in Java?


Definition and Usage. The try keyword creates a try... catch statement. The try
statement allows you to define a block of code to be tested for errors while it is being
executed. The catch statement allows you to define a block of code to be executed, if
an error occurs in the try block.

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. There might be a list of the methods
that had been called to get to the method where an exception occurred. This
ordered list of 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
a block of code that can handle the occurred exception. The block of the
code is called an Exception handler.
• The run-time system starts searching from the method in which the
exception occurred and proceeds through the call stack in the reverse order
in which methods were called.
• If it finds an appropriate handler, then it passes the occurred exception to it.
An appropriate handler means the type of exception object thrown matches
the type of exception object it can handle.
• If the run-time system searches all the methods on the call stack and
couldn’t have found the appropriate handler, then the run-time system
handover the Exception Object to the default exception handler, which is
part of the run-time system. This handler prints the exception information in
the following format and terminates the program abnormally.
Exception in thread "xxx" Name of Exception : Description
... ...... .. // Call Stack
Look at the below diagram to understand the flow of the call stack.

How to Use the Try-catch Clause?


try {
// block of code to monitor for errors
// the code you think can raise an exception
} catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally { // block of code to be executed after try block ends
}

Certain key points need to be remembered that are as follows:


• In a method, there can be more than one statement that might throw an
exception, So put all these statements within their own try block and provide
a separate exception handler within their own catch block for each of them.
• If an exception occurs within the try block, that exception is handled by the
exception handler associated with it. To associate the exception handler, we
must put a catch block after it. There can be more than one exception
handler. Each catch block is an exception handler that handles the
exception to the type indicated by its argument. The argument,
ExceptionType declares the type of exception that it can handle and must be
the name of the class that inherits from the Throwable class.
• For each try block, there can be zero or more catch blocks, but only
one final block.
• The finally block is optional. It always gets executed whether an exception
occurred in try block or not. If an exception occurs, then it will be executed
after try and catch blocks. And if an exception does not occur, then it will
be executed after the try block. The finally block in Java is used to put
important codes such as clean-up code e.g., closing the file or closing the
connection.
• If we write System.exit in the try block, then finally block will not be executed.
The summary is depicted via visual aid below as follows:
Java try and catch
The try statement allows you to define a block of code to be tested for errors
while it is being executed.

The catch statement allows you to define a block of code to be executed, if an


error occurs in the try block.

The try and catch keywords come in pairs:

SyntaxGet your own Java Server


try {

// Block of code to try

}
catch(Exception e) {

// Block of code to handle errors

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {

public static void main(String[ ] args) {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]); // error!

The output will be something like this:

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)

Try it Yourself »

If an error occurs, we can use try...catch to catch the error and execute some
code to handle it:

Example
public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");


}

The output will be:

Something went wrong.

Try it Yourself »

Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:

Example
public class Main {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

} finally {

System.out.println("The 'try catch' is finished.");

}
}

The output will be:

Something went wrong.


The 'try catch' is finished.

Try it Yourself »

we had to catch only one exception type in each catch block. So, whenever
we needed to handle more than one specific exception but take some action
for all exceptions, we had to have more than one catch block containing the
same code.

it is possible for a single catch block to catch multiple exceptions by separating


each with | (pipe symbol) in the catch block.
Catching multiple exceptions in a single catch block reduces code duplication
and increases efficiency. The bytecode generated while compiling this program
will be smaller than the program having multiple catch blocks as there is no
code redundancy.

Syntax:
try {
// code
}
catch (ExceptionType1 | Exceptiontype2 ex){
// catch block
}
Flow Chart of Java Multiple Catch Block
FINALLY:-

Java finally block


Java finally block is a block used to execute important code such as closing the
connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block


1.Control flow in try-catch clause OR try-catch-finally clause
• Case 1: Exception occurs in try block and handled in catch block
• Case 2: Exception occurs in try-block is not handled in catch block
• Case 3: Exception doesn’t occur in try-block
2. try-finally clause
• Case 1: Exception occurs in try block
• Case 2: Exception doesn’t occur in try-block
Control flow in try-catch OR try-catch-finally
1. Exception occurs in try block and handled in catch block: If a statement
in try block raised an exception, then the rest of the try block doesn’t execute
and control passes to the corresponding catch block. After executing the catch
block, the control will be transferred to finally block(if present) and then the rest
program will be executed.
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception is
pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to be
nested.

Syntax:

1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block

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.
Syntax in Java throw
throw Instance
Example:
throw new ArithmeticException("/ by zero");
But this exception i.e., Instance must be of type Throwable or a subclass
of Throwable.

Java throws
throws is a keyword in Java that is used in the signature of a method to indicate
that this method might throw one of the listed type exceptions. The caller to
these methods has to handle the exception using a try-catch block.
Syntax of Java throws
type method_name(parameters) throws exception_list

exception_list is a comma separated list of all the


exceptions which a method might throw.
In a program, if there is a chance of raising an exception then the compiler
always warns us about it and compulsorily we should handle that checked
exception, Otherwise, we will get compile time error saying unreported
exception XXX must be caught or declared to be thrown. To prevent this
compile time error we can handle the exception in two ways:
1. By using try catch
2. By using the throws keyword
We can use the throws keyword to delegate the responsibility of exception
handling to the caller (It may be a method or JVM) then the caller method is
responsible to handle that exception.

INTERFACE:-

The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface, not the method body. It is used to
achieve abstraction and multiple inheritances in Java using Interface. In other
words, you can say that interfaces can have abstract methods and variables.
Syntax for Java Interfaces
interface {

// declare constant fields


// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total
abstraction. That means all the methods in an interface are declared with an
empty body and are public and all fields are public, static, and final by default. A
class that implements an interface must implement all the methods declared in
the interface. To implement the interface use the implements keyword.

Uses of Interfaces in Java


Uses of Interfaces in Java are mentioned below:
• It is used to achieve total abstraction.
• Since java does not support multiple inheritances in the case of class, by
using an interface it can achieve multiple inheritances.
• Any class can extend only 1 class but can any class implement an infinite
number of interface.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy