0% found this document useful (0 votes)
22 views10 pages

Java Exception Handling Explained

The document discusses exception handling in Java, outlining the importance of managing errors to prevent program crashes. It categorizes errors into compile-time and run-time errors, explains the concept of exceptions, and details the syntax for handling exceptions using try, catch, and finally blocks. Additionally, it covers user-defined exceptions and the throws keyword for method declarations, providing examples for clarity.

Uploaded by

parnaskiran
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)
22 views10 pages

Java Exception Handling Explained

The document discusses exception handling in Java, outlining the importance of managing errors to prevent program crashes. It categorizes errors into compile-time and run-time errors, explains the concept of exceptions, and details the syntax for handling exceptions using try, catch, and finally blocks. Additionally, it covers user-defined exceptions and the throws keyword for method declarations, providing examples for clarity.

Uploaded by

parnaskiran
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

UNIT 3

EXCEPTION HANDLING

Introduction:

Errors are wrongs that can make a program go wrong. An error may produce incorrect output or may
terminate the execution of the program abruptly or even may cause the system to crash. It is therefore
important to detect and manage properly all the error conditions in the program so that the program will
not terminate or crash during execution.

Types of Errors:

Errors may broadly be classified into two categories:


 Compile-time errors
 Run-time errors

Compile-time errors:
All syntax errors will be detected and displayed by the Java compiler and therefore theses errors are
known as compile-time errors.
Most of the compile-time errors are due to typing mistakes. Typographical errors are hard to find. We
have to check the code word by word, or even character by character. The most common problems are:
 Missing semicolons
 Missing (or mismatch of) brackets in classes and methods
 Misspelling of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables
 Incompatible types in assignments/initialization
 Bad references to objects
 Use of = in place of = = operator
 And so on

Run-time errors:
Sometimes program may compile successfully creating the .class file but may not run properly. Such
programs may produce wrong results due to wrong logic or may terminate due to errors such as stack
overflow. Most common run-time errors are:
 Dividing an integer by zero
 Accessing an element that is out of the bounds of an array
 Trying to store a value into an array of an incompatible class or type
 Trying to cast an instance of a class to one of its subclasses
 Passing a parameter that is not in a valid range or value for a method
 Trying to illegally change the state of a thread
 Attempting to use a negative size for an array
 Using a null object reference as a legitimate object reference to access a method or a variable
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string
 And many more

PARNASHREE S, SKPFGC Page 1


UNIT 3

Exceptions:
An exception is a condition that is caused by a run-time error in the program. When the Java
interpreter encounters an error such as dividing an integer by zero, it creates an exception object and
throws it (i.e., informs us that an error has encountered).

If the exception object is not caught and handles properly, the interpreter will display an error
message and terminate the program. If we want the program to continue with the execution of the
remaining code, then we should try to catch the exception object thrown by the error condition and
then display an appropriate message for taking corrective actions. This task is known as exception
handling.

The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional
circumstances” so that appropriate action can be taken. The mechanism suggests incorporation of a
separate error handling code that performs the following tasks:

1. Find the problem (Hit the exception).


2. Inform that an error has occurred (Throw the exception).
3. Receive the error information (Catch the exception).
4. Take corrective actions (Handle the exception).
The error handling code basically consists of two segments, one to detect errors and to throw exception
and the other to catch exceptions and to take appropriate actions.

Common Java Exceptions: Different types of exceptions

Exception Type Cause of Exception


ArithmeticException Caused by math errors such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes
ArrayStoreException Caused when a program tries to store the wrong type of data in an
array
FileNotFoundException Caused by an attempt to access a nonexistent file
IOException Caused by general I/O failures, such as inability to read from a file
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between strings and number fails
OutOfMemoryException Caused when there’s not enough memory to allocate a new object
SecurityException Caused when an applet tries to perform an action not allowed by
the browser’s security setting.
StackOverflowException Caused when the system runs out of stack space
StringIndexOutOfBoundsException Caused when a program attempts to access a nonexistent character
position in a string

PARNASHREE S, SKPFGC Page 2


UNIT 3

Syntax of Exception handling code:


The basic concepts of exception handling are throwing an exception and catching it. This is illustrated in
below fig.

try Block
Exception object
Statement that
creator
causes an exception
throws
exception object

catch Block

Statement that Exception


handles the exception handler

fig: Exception handling mechanism

 Java uses a keyword try to preface a block of code that is likely to cause an error condition and
“throw” an exception.
 A catch block defined by the keyword catch “catches” the exception “thrown” by the try block
and handles it appropriately. The catch block is added immediately after the try block. The
following example illustrates the use of simple try and catch statements.

………………….
………………….
try
{
statement; // generates an exception
}
catch(Exception-type e)
{
Statement; // processes the exception
}
………………….
………………….

The try block can have one or more statements that could generate an exception. If any one statement
generates an exception, the remaining statements in the block are skipped and execution jumps to the
catch block that is placed next to try block.

PARNASHREE S, SKPFGC Page 3


UNIT 3

The catch block too can have one or more statements that are necessary to process the exception.
Remember that every try statements should be followed by at least one catch statement; otherwise
compilation error will occur.

Note that the catch statement works like a method definition. The catch statement is passed a single
parameter, which is reference to the exception object thrown (by the try block). If the catch parameter
matches with the type of exception object, then the exception is caught and statements in the catch block
will be executed. Otherwise, the exception is not caught and the default exception handler will cause the
execution to terminate.

Program: Illustrates the use of try and catch blocks to handle an arithmetic exception.

class Error3
{
public static void main(String args[ ])
{
int a = 10;
int b= 5;
int c = 5;
int x, y;
try
{
x = a/(b-c); // Exception here
}
catch(ArithmeticException e)
{
[Link](“division by zero”);
}
y = a/(b+c);
[Link](“y = ” +y);
}
}

Output:
Division by zero
y=1

Note that the program did not stop at the point of exceptional condition. It catches the error condition,
prints the error message, and then continues the execution, as if nothing has happened.

PARNASHREE S, SKPFGC Page 4


UNIT 3

Multiple catch statements:


It is possible to have more than one catch statement in the catch block as illustrated below:
……………..
……………..
try
{
statement; // generates an exception
}
catch(Exception-Type-1 e)
{
statement; // produces exception type 1
}
catch(Exception-Type-2 e)
{
statement; // produces exception type 2
}
.
.
.
catch(Exception-Type-N e)
{
statement; // produces exception type N
}
……………..
……………..
When an exception in a try block is generated, the Java treats the multiple catch statements like cases in a
switch statement. The first statement whose parameter matches with the exception object will be
executed, and the remaining statements will skipped.

Note that Java does not require any processing of the exception at all. We can simply have a catch
statement with an empty block to avoid program abortion.

Example:
catch(Exception e);
The catch statement simply ends with a semicolon, which does nothing. This statement will catch an
exception and then ignore it.

PARNASHREE S, SKPFGC Page 5


UNIT 3

Program: Using multiple catch blocks.


class Error4
{
public static void main(String args[ ])
{
int a[ ] = {5,10};
int b = 5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
[Link]("division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index error");
}
catch(ArrayStoreException e)
{
[Link]("wrong data type");
}
int y=a[1]/a[0];
[Link]("y = " +y);
}
}
Output:
Array index error
y=2

Note that the array element a[2] does not exist because array a is defined to have only two elements, a[0]
and a[1]. Therefore, the index 2 is outside the array boundary thus causing the block
catch(ArrayIndexOutOfBoundsException e)
to catch and handle the error. Remaining catch blocks are skipped.

Using finally statement:

Java supports another statement known as finally statement that can be used to handle an exception that is
not caught by any of the previous catch statements.

finally block can be used to handle any exception generated within a try block. It may be added
immediately after the try block or after the last catch block shown as follows:

PARNASHREE S, SKPFGC Page 6


UNIT 3

1. try
{
……………..
……………..
}
finally
{
……………..
……………..
}

2. try
{
……………..
……………..
}
catch(….)
{
……………..
……………..
}
catch(….)
{
……………..
……………..
}
.
.
.
finally
{
……………..
……………..
}

When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is
thrown. As a result, we can perform certain house-keeping operations such as closing files and releasing
system resources.

PARNASHREE S, SKPFGC Page 7


UNIT 3

User defined Exception using try-catch-finally-throw blocks (Throwing our own exceptions):

In Java, a user-defined exception is a custom exception created by extending the Exception


class (or one of its subclasses). This allows you to define specific types of errors that are relevant
to your application. You can create your own exceptions when the built-in exceptions don't meet
your needs.

Steps to create a user-defined exception:

1. Create a class that extends Exception (for checked exceptions) or RuntimeException


(for unchecked exceptions).
2. Define constructors in the custom exception class to pass messages or other information.

We can do this by using the keyword throw as follows:


throw new Throwable_subclass;

throw new ArithmeticException( );


throw new NumberFormatException( );

Note: throw Keyword in Java

The throw keyword in Java is used to explicitly throw an exception. It is different from throws, which is
used in method signatures to declare exceptions.

Below program demonstrates the use of a user-defined subclass of Throwable class. Note that Exception
is a subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a
class that extends Throwable can be thrown and caught.

Example Program: Throwing our own Exception

import [Link];
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}

class TestMyException
{
public static void main(String args[ ])
{
int x = 5, y = 1000;
try

PARNASHREE S, SKPFGC Page 8


UNIT 3

{
float z = (float)x/(float)y;
if(z < 0.01)
{
throw new MyException("Number is too small");
}
}
catch(MyException e)
{
[Link]("caught my exception");
[Link]([Link]( ));
}
finally
{
[Link]("I am always here");
}
}
}

Output:
Caught my exception
Number is too small
I am always here

Nested Try Blocks in Java


A nested try block is a try block inside another try block. This is useful when handling multiple levels of
exceptions, where an inner block might handle specific exceptions, and the outer block handles more
general ones.
public class NestedTryExample {
public static void main(String[] args) {
try {
[Link]("Outer try block started.");

try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // This will cause an ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner catch: Array index is out of bounds!");
}

// This statement will still execute because the inner exception was handled.
int result = 10 / 0; // This will cause an ArithmeticException
}

PARNASHREE S, SKPFGC Page 9


UNIT 3

catch (ArithmeticException e) {
[Link]("Outer catch: Cannot divide by zero!");
}
[Link]("Program continues...");
}
}
OUTPUT:
Outer try block started.
Inner catch: Array index is out of bounds!
Outer catch: Cannot divide by zero!
Program continues...

throws Keyword in Java

The throws keyword in Java is used in method declarations to specify that a method might throw one or
more exceptions. It informs the caller of the method that it must handle or propagate these exceptions.

Syntax of throws
returnType methodName(parameters) throws ExceptionType1, ExceptionType2
{
// Method code
}

 throws is used in the method signature.


 It is followed by one or more exception types, separated by commas.

Example: Using throws with a Built-in Exception

public class ThrowsExample {


static void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
[Link]("Result: " + (a / b));
}

public static void main(String[] args) {


try {
divide(10, 2); // Works fine
divide(10, 0); // Throws an exception
} catch (ArithmeticException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}
Output:
Result: 5
Caught Exception: Cannot divide by zero!

PARNASHREE S, SKPFGC Page 10

Common questions

Powered by AI

Checked exceptions represent error conditions that are catchable and recoverable, and they are checked at compile time. Examples include IOException and FileNotFoundException. They must be declared in a method's throws clause if not handled within the method. Unchecked exceptions, such as NullPointerException and ArithmeticException, occur during runtime and can be avoided through proper programming logic, but they do not require explicit handling or declaration. The distinction affects error handling by imposing a compile-time requirement on handling checked exceptions, ensuring that developers anticipate and manage these situations, while unchecked exceptions allow more flexible handling strategies .

A catch block in Java must match the exception type to properly catch and handle the specific error. This ensures that the right corrective actions are taken for the particular error encountered. If no catch block matches the exception type, the exception remains unhandled, and the program enters the default exception handling mechanism, potentially terminating the program with an error message. Incorrect or unmatched catch blocks lead to the failure of intended exception management and program continuation .

A user-defined exception in Java is a custom exception type created by extending the Exception class or one of its subclasses, allowing for specific error handling tailored to an application's unique needs. Implementation involves creating a new class that extends Exception, optionally providing constructors to enable message passing. This enables the application to throw meaningful exceptions tailored to particular logic errors or conditions that built-in exceptions do not cover. For instance, a custom exception can be used to handle a domain-specific error, such as a validation failure of a complex business rule .

The throw keyword in Java is used to explicitly throw an exception, allowing the program to initiate the exception handling process manually. This can be used to indicate exceptional conditions in a program logic that require attention. By contrast, the throws keyword is used in method signatures to declare that a method can throw certain exceptions, informing the caller that those exceptions must be handled. A method that uses throws delegates the responsibility of handling exceptions to the caller .

A finally block in Java is used to execute important code such as resource release, regardless of whether an exception occurs or not. Its significance lies in providing a mechanism to execute cleanup operations or other necessary code after a try-catch block, ensuring that such operations run to completion even if unexpected exceptions occur. This guarantees that resources like file handles and network connections are properly closed, preventing resource leaks .

Java errors can be classified into compile-time errors and run-time errors. Compile-time errors occur when there are syntax mistakes, such as missing semicolons or mismatched brackets, which prevent the program from compiling successfully. These errors are detected by the compiler and typically arise from typographical mistakes. On the other hand, run-time errors occur after the program has been successfully compiled. These errors occur during execution and can cause the program to terminate unexpectedly or produce incorrect results. Examples include dividing by zero or accessing an array out of bounds .

Both IOException and FileNotFoundException are examples of checked exceptions, requiring either handling via try-catch blocks or declaration with throws in method signatures. They typically represent errors related to input/output operations when a file cannot be accessed or manipulated as expected. These exceptions exemplify common use cases where precursor conditions, such as file availability checks before reading, can mitigate exception occurrences, and mandatory handling ensures these scenarios are anticipated and managed, preventing program crashes due to I/O errors .

Multiple catch blocks in Java provide a mechanism to handle different exception types separately, each catch block corresponding to a specific exception. When an exception occurs in a try block, Java evaluates the catch blocks sequentially, similar to cases in a switch statement. The first catch block that matches the type of the thrown exception gets executed, and the subsequent catch blocks are ignored. This structured approach allows fine-grained error handling and improves code readability and robustness .

Nested try blocks enhance exception handling by allowing more granular control over different levels of exceptions within the same execution context. Each inner try block can handle specific exceptions with its own catch blocks, allowing the outer try block to catch general or unhandled exceptions. This is useful when dealing with complex operations that may generate multiple types of exceptions at different stages. For example, reading data from a file while parsing its content could involve an inner try block to handle file I/O errors and an outer try block to handle parsing errors .

Java's exception handling mechanism ensures program robustness by allowing developers to manage and respond to unexpected conditions or errors that occur during program execution. The process involves four key steps: finding the error (the exception is hit), informing that an error has occurred (throwing the exception), receiving the error information (catching the exception), and taking corrective actions (handling the exception). By using try-catch blocks, programs can continue execution even after an error has been encountered, as opposed to terminating abruptly .

You might also like