Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views13 pages

Chapter 5

This chapter discusses exception handling in Java, explaining that exceptions are unexpected events that disrupt program execution. It outlines the keywords used for exception handling, such as try, catch, throw, throws, and finally, and provides examples of handling exceptions, including multiple catch statements. Additionally, it describes the hierarchy of exception types and the consequences of uncaught exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views13 pages

Chapter 5

This chapter discusses exception handling in Java, explaining that exceptions are unexpected events that disrupt program execution. It outlines the keywords used for exception handling, such as try, catch, throw, throws, and finally, and provides examples of handling exceptions, including multiple catch statements. Additionally, it describes the hierarchy of exception types and the consequences of uncaught exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Chapter-5

EXCEPTION HANDLING
Introduction to Exception Handling:

• An Exception is an unwanted or unexpected event that occurs during the execution of a


program (i.e., at runtime) and disrupts the normal flow of the program’s instructions.
• It occurs when something unexpected happens, like accessing an invalid index, dividing
by zero, or trying to open a file that does not exist.
• Java provides a way to handle such errors using exception handling.
• A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code. When an exceptional condition arises, an object
representing that exception is created and thrown in the method that caused the error.
• Exceptions can be generated by the Java run-time system, or they can be manually
generated by our code.
• Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
language or the constraints of the Java execution environment.
• Manually generated exceptions are typically used to report some error condition to the
caller of a method.
• Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally
Keywords in Exception Handling:

• try block contains program statements that are to be to monitored for exceptions
– If an exception occurs within the try block, it is thrown

• catch block contain statements that catch this exception and handle it in some
rational manner – System-generated exceptions are automatically thrown by the
Java runtime system.

• throw is used to manually throw an exception.

• throws clause is used to specify any exception that is thrown out of a method.

• finally block contains code that absolutely must be executed after a try block
completes.
Aspect throw throws

To actually throw an To declare potential


Use
exception exceptions

Location Inside method or block In the method declaration

Throws one exception at Can declare multiple


Number
a time exceptions

public void m() throws


Example throw new IOException();
IOException {}
Basic try catch syntax:

try
{
// Code that might throw an exception
}
catch (ExceptionType e)
{
// Code to handle the exception
}
Using try and Catch:
• Although the default exception handler provided by the Java run-time system is useful for
debugging, you will usually want to handle an exception yourself. Doing so provides two
benefits.
• First, it allows you to fix the error.
• Second, it prevents the program from automatically terminating.
• To guard against and handle a run-time error, simply enclose the code that you want to
monitor inside a try block.
• Immediately following the try block, include a catch clause that specifies the exception
type that you wish to catch.
• To illustrate how easily this can be done, the following program includes a try block and a
catch clause that processes the ArithmeticException generated by the division-by-zero
error:
Example try and Catch:

class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
} finally { // Finally Block
System.out.println("This is the finally block.");
}
System.out.println("After catch statement.");
}
}

• Notice that the call to println( ) inside the try block is never executed. Once an exception
is thrown, program control transfers out of the try block into the catch block.
Exception Types:

• All exception types are subclasses of the


built-in class Throwable
• Below Throwable are two subclasses that
partition exceptions into two branches

• Exception class: used for exceptional


conditions that user programs should catch
• RuntimeException etc are subclasses
of Exception.

• Error class: used by the Java runtime


system to indicate errors having to do
with the run-time environment (eg
Stack overflow)

• Every Exception type is basically an object


belonging to class Exception
Uncaught Exception:
• Before you learn how to handle exceptions in your program, it is useful to see what
happens when you don’t handle them. This small program includes an expression that
intentionally causes a divide-by-zero error:
class ExcDemo {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
• When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception. This causes the execution of Exc0 to
stop, because once an exception has been thrown, it must be caught by an exception
handler and dealt with immediately.
• Any exception that is not caught by your program will ultimately be processed by the
default handler and it displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program.
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Multiple catch statements:

• You can catch different types of exceptions separately.


• Useful for handling multiple error types differently.
• Use when more than one exception could be raised by a single piece of code.
• When an exception occurs, only the first matching catch block is executed. The rest are
skipped.
• Makes error handling clearer, more maintainable, and easier to debug compared to a
single, generic catch block.
Syntax:
try
{
statements;
}
catch(ExceptionType1 e1)
{
statements;
}
catch(ExceptionType2 e2)
{
statements;
}
catch(ExceptionType3 e3)
{
statements;
}
...
catch(ExceptionTypen en)
{
statements;
}
Example:

class MultiCatchExample {
public static void main(String args[]) {
try {
int a = 10, b = 0;
int result = a / b; // divide-by-zero error
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // array index out of bounds
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
}
System.out.println(“After try/Catch Blocks.");
}
}

You might also like