0% found this document useful (0 votes)
2 views8 pages

Chapter 6 - Exception Handling

Chapter Six covers exception handling in Java, explaining that exceptions are runtime errors that disrupt the normal flow of a program. It details the types of exceptions, including checked and unchecked exceptions, and provides syntax for using try, catch, and finally blocks to manage these exceptions effectively. The chapter also illustrates various examples demonstrating how to handle exceptions and the importance of proper exception management in Java programming.

Uploaded by

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

Chapter 6 - Exception Handling

Chapter Six covers exception handling in Java, explaining that exceptions are runtime errors that disrupt the normal flow of a program. It details the types of exceptions, including checked and unchecked exceptions, and provides syntax for using try, catch, and finally blocks to manage these exceptions effectively. The chapter also illustrates various examples demonstrating how to handle exceptions and the importance of proper exception management in Java programming.

Uploaded by

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

Chapter Six: Exception Handling

6.1. Exception Handling Overview


An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a runtime error. In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime. If an exception occurs and your program do not handled it, your
program will crash. Meaning your program stops execution after the exception occurs. But if your
program handled the exception, your program continues to execute whether or not runtime error
happened.
A java exception is an object that describes an exceptional condition that has occurred in a piece of code
at runtime. When an exception arises, an object representing that exception is created and thrown in the
method that caused the error. That method may choose to handle the exception itself, or pass it on.
Either way, at some point, the exception is caught and processed. Exceptions can be generated by the
Java runtime system, or they can be manually generated by your code. Exceptions generated by java are
the fundamental errors that violate the rules of the java language or constraints of the java execution
environment such as division by zero, trying to open a file for reading that does not exist, etc. Manually
generated exceptions are typically used to report some error condition to the caller of a method.
There are five keywords to work with exception in java. These are try, catch, throw, throws, and
finally. The statements that may arise runtime error are constrained within a try block. If an exception
occurs within the try block, it is thrown. This exception is handled by the catch block.
The general syntax of using the try..catch..finally is as follows.
try{
//statements that may arise runtime errors
}
catch(ExceptionType1 ob){
//exception handler code for ExceptionType1
}
catch(ExceptionType2 ob){
//exception handler code for ExceptionType2
}
//you can as many catch blocks
finally{
//statements to be executed after the try block ends
}

6.2. Exception Types


All exception types are subclasses of the built-in class Throwable. This class has two subclasses:
Exception and Error. The Exception class is used for exceptional conditions that user programs should
catch. It is also the class that you will subclass to create your own custom exception types. The Error
class is used by the java runtime system to indicate errors having to do with the runtime environment.
Stack overflow is an example of such an error.
There are many subclasses of the Exception class. One of them is the RuntimeException class that in
turn has many subclasses that are the main objectives of this chapter. All the subclasses of the
RuntimeException are in the java.lang package, as a result we don’t need to import them. There are
Page 1 of 8
many subclasses of the Exception class. Two of them and some of their subclasses are shown in the
table below.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions


1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptionsarenotchecked at compile-timeratherthey arechecked at runtime.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionErroretc.

Page 2 of 8
Subclasses Description
- ArithmeticException Arithmetic error such division by zero
- ArrayIndexOutOfBoundsException Array index out of bounds
RuntimeException

- ArrayStoreException Storing to an array element of an incompatible type


- ClassCastException Invalid cast
- NegativeArraySizeException Array created with a negative size
- NullPointerException Invalid use of null (uninitialized) reference
- StringIndexOutOfBoundsException Attempt to index outside the bounds of a string
- ClassNotFoundException Class not found
- EOFException Attempting to read after the end of file is reached
IOException

- FileNotFoundException Attempting to read a file that does not exist


- NotSerializableException Attempting to write an object into a file that does
not implement the Serializable interface

6.3. How to use the tr…catch…finally block


6.3.1. A Program without Exception Handling
The following program demonstrates what will happen if a runtime error occurs.

class ExceptionExample{ This program will


public static void main(String args[]){ successfully compile. But
int x = 10, y = 0; when it runs it throws a
System.out.println(x/y); runtime error because of
System.out.println("this will not be division by zero. All
displayed"); statements after the
} exception will not Page be 3 of 8
} executed The result is shown
by the following figure.
The following program will also demonstrate what will happen if we use out of bound index for array.
class ExceptionExample2{ This program will also raise a
public static void main(String a[]){ runtime error since invalid
float x[] = {5,6,3,4,7,8}; array index is used.
for(int i = 6; i>0; i--) The following figure shows
the output.
System.out.println(x[i]);
System.out.println("This will not be executed");
}
}

To avoid such runtime errors we need to use the try… catch … finally block.
6.3.2. Using Exception
The syntax:
try{
//statements that may arise runtime errors
}
catch(ExceptionType1 ob){
//exception handler code for ExceptionType1
}
catch(ExceptionType2 ob){
//exception handler code for ExceptionType2
}
//you can as many catch blocks
finally{
//statements to be executed after the try block ends
}
The try block contains statements that may raise an exception. When the exception occurs, an Exception
object of the correct type is created and thrown to the catch block that has a matching argument with the
created object type. The statements after the erroneous statement are jumped and execution goes to the
catch block. The catch block receives the exception description using its object argument. Then
statements in the catch block are executed only when an exception occurs in the try block.
The final block will be executed whether exception happened or not. It is used to do some finalizing
tasks such as closing opened files etc. The final block is optional.

Page 4 of 8
The following program demonstrates how to use the try..catch...finally block.
class ExceptionExample3{ Here when the exception
public static void main(String args[]){ occurs an
int x = 10, y = 0; ArithmeticException object
try{ is created and thrown to the
System.out.println(x/y);
catch block that has a
System.out.println("This will not be executed");
}
matching argument. The
catch(ArithmeticException ex){ statements after the
System.out.println("Division by zero"); erroneous statement in the
} try block will not be
finally{ executed. The statements in
System.out.print("This block is executed "); the catch block will be
System.out.println("whether or not exception occurs"); executed and everything
} after the catch block will be
System.out.println("this will be displayed now"); executed.
}
}

The following program corrects the array index out of bounds error.

class ExceptionExample4{ In the first iteration of the


public static void main(String a[]){ loop a runtime error occurs
float x[] = {5,6,3,4,7,8}; because of invalid index. In
for(int i = 6; i>0; i--){ this case, statements after
try{ the error are jumped and
System.out.println(x[i]); control goes to the catch
System.out.println("In the try block"); block. The catch block
} displays a message.
catch(ArrayIndexOutOfBoundsException ex){
Then the final block
System.out.println(i + " is not valid index");
executes.
}
finally{ Then the loop continues
System.out.println("In the final block"); without error.
} The following picture
} shows the output.
System.out.println("Outside the loop");
}
}

Page 5 of 8
One or more catch blocks can be used. The block with a matching exception type will be selected and
executed. The following program demonstrates how.
class ExceptionExample5{ Having more than one catch
public static void main(String args[]){ blocks is important when one
int x = 10, y = 0; or more type of exceptions
try{ will be raised by the
System.out.println(x/y); statements in the try block.
System.out.println("This will not be executed");
In this example only the
}
catch block with
catch(ArrayIndexOutOfBoundsException ex){
ArithmeticException will
System.out.println("Invalid Array Index");
receive the exception thrown
}
by the try block.
catch(StringIndexOutOfBoundsException ex){
System.out.println("Invalid String Index");
}
catch(ArithmeticException ex){
System.out.println("Division by zero");
}
finally{
System.out.print("This block is executed ");
System.out.println("whether or not exception occurs");
}
System.out.println("this will be displayed now");
}
}

Super classes can be used as arguments to the catch block. This is possible because a superclass
reference variable can refer to the subclass’ object.
class ExceptionExample6{
public static void main(String a[]){
int x = 10, y = 0;
try{
System.out.println(x/y);
}
catch(RuntimeException e){
if(e instanceof ArithmeticException)

Page 6 of 8
System.out.println("Division By Zero");
else
System.out.println("Runtime error");
}

}
}

But if subclasses are used together with superclasses, the catch blocks with superclass object arguments
must be at the end. Otherwise compiler error will happen.

class ExceptionExample7{ This program has a compile time


public static void main(String a[]){ error since the catch with
int x = 10, y = 0; ArithmeticException argument is
try{ written after the catch with
System.out.println(x/y); RuntimeException argument. This
} happens because RuntimeException
catch(RuntimeException e){ is superclass of
System.out.println("Runtime error occurs"); ArithmeticException.
}
catch(ArithmeticException ex){
System.out.println("Division by zero");
}
}
}

Java throw keyword


The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly
used to throw custom exception.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){ validate(13);
System.out.println("rest of the code...");
}}
Java throws keyword
The Java throws keyword is used to declare an exception. 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.
Write a program to accept & display the month number .throw an number format
exception if improper month number is enter?

Page 7 of 8
Page 8 of 8

You might also like