Topic 4
Topic 4
also known as IO
Exception
Definition of Exceptions
✘ An exception (or exceptional event) is a problem
that arises during the execution of a program.
When an Exception occurs the normal flow of
the program is disrupted and the program (or
application) terminates abnormally, which is not
recommended, therefore these exceptions are to
be handled.
6
Exception
When an exception
occurs, the Java virtual
Exception is a problem Eg: bad user input, or
machine creates an object
that occurs when a mechanical failure of an
of class Exception which
program is running. I/O device.
holds information about
the problem.
7
Exception Scenarios
✘ An exception can occur for many different reasons,
below given are some scenarios where exception
occurs:
✘ A user has entered invalid data.
✘ A file that needs to be opened cannot be found.
✘ A network connection has been lost in the middle of
communications or the JVM has run out of memory.
✘ Noted: Some of these exceptions are caused by user
error, others by programmer error, and others by
physical resources that have failed in some manner.
1-9
Exceptions
✘ An exception is an object that describes an unusual or
erroneous situation
✘ Exceptions are thrown by a program, and may be
caught and handled by another part of the program
✘ A program can be separated into a normal execution
flow and an exception execution flow
✘ An error is also represented as an object in Java, but
usually represents a unrecoverable situation and
should not be caught
Error
✘ Error is a problem that occurs when a program is
running.
✗ Eg: Wrong output, abrupt termination of the
program, crashing of the system
✘ Represented by an object of class Error.
✘ But an error is too severe for a program to
handle.
✘ The program must stop running.
Type of Error
✘ Generally, in any language there are two broad
classification of errors:
✘ Compile Time errors
✗ Errors that occur due to wrong syntax in the
program.
✗ Detected by compilers and .class file not created.
✘ Runtime errors
✗ Errors that occur while executing a program.
✗ The .class file are created but may not run
properly.
Problem 2
✘ Are Error objects and Exception objects
related?
Error?
Exception?
Concept of Exception
Handling
✘ Class Exception and class Error both extend
Throwable.
✘ Exceptions are different from Errors because
programs can be written to recover from
Exceptions, but programs can not be written to
recover from Errors.
✘ Exceptions can be caught by a part of the
program that tries to recover from the problem.
Concept of Exception Handling
✘ Hierarchy of Throwable
class
✘ Java exception can be
manually generated
✗ by the code
✗ by the Java runtime
system during the
program execution.
Exception Handling
Mechanism
✘ Exceptions are handled in Java using the
five keywords :
✗ try
✗ catch
✗ throw
✗ throws
✗ finally
Using Exception Handling
✘ To catch an Exception:
try
✗ Put code that might
throw an Exception
inside a try{} block.
✗ Put code that
catch
handles the
Exception inside a
catch{} block. finally
Syntax
try
{
// statements which might throw
// various types of exceptions
}
catch ( SomeExceptionType ex )
{
// statements to handle this
// type of exception
}
// Statements following the structure
Try and catch
✘ The statements in the try{} block can include:
✗ Statements that always work.
✗ Statements that might throw an Exception of one type or
another.
✘ One or several catch{} blocks follow the try() block.
✗ Sometimes there can be no catch{} blocks.
✘ Each catch{} block describes the type of Exception it catches.
✗ It does this in a one-item parameter list: ( ExceptionType
parameter )
✗ the parameter is a reference variable that will refer to the
Exception object when it is caught.
Try and catch
Using Exception Handling
✘ If a statement inside the try{} block throws a
InputMismatchException, the catch{} block
immediately starts running.
✘ The remaining statements in the try{} block are
skipped.
✘ After the catch{} block is executed, execution
continues with the statement that follows the catch{}
block.
✘ Execution does not return to the try{} block.
Catching Exceptions
▪ A method catches an exception using a combination of
the try and catch keywords.
▪ A try/catch block is placed around the code that might
generate an exception.
▪ Code within a try/catch block is referred to as protected
code, and the syntax for using try/catch looks like the
following: try
{
// Protected code
} catch(ExceptionName e1)
{
// Catch block
}
Catching Exceptions
✘ The code which is prone to exceptions is placed in the try
block, when an exception occurs, that exception occurred is
handled by catch block associated with it. Every try block
should be immediately followed either by a class block or
finally block.
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown: " + e);
}
Output:
}
Exception thrown:
}
java.lang.ArrayIndexOutOfBoundsException: 3
class ArrayExcepDemo
{
public static void main(String args[])
{
int var[]={5,10};
try
{
int x = var[2]-var[1];
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array subscript
out of range");
}
}
}
Output:
Array subscript out of range
Multiple catch Blocks
✘ A try block can be try {
followed by //Protected code
followed by
//Protected code
} catch(ExceptionType1 e1) {
multiple catch //Catch block
the following:
}
Note: You can have any number of them after a single try. If an exception occurs in the protected code, the exception is
thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught
there. If not, the exception passes down to the second catch statement. This continues until the exception either is
caught or falls through all catches, in which case the current method stops execution and the exception is thrown down
to the previous method on the call stack.
Multiple catch Blocks
✘ class MultipleCatchDemo
✘
✘
{
public static void main(String args[])
✘ {
✘
✘
try {
int num1 = 30, num2 = 0;
✘ int output = num1 / num2;
✘
✘
System.out.println ("Result = " + output);
}
✘ catch(NumberFormatException e){
✘
✘
System.out.println("NumberFormatException occurred");
}
✘ catch(ArrayIndexOutOfBoundsException e){
✘ System.out.println ("ArrayIndexOutOfBounds occurred");
✘ }
✘ catch(ArithmeticException e){
✘
✘
System.out.println ("ArithmeticException occurred");
} Output:
✘ }
✘
ArithmeticException
} occurred
throws Keywords
✘ If a method does not handle a checked exception, the
method must declare it using the throws keyword. The
throws keyword appears at the end of a method's signature.
✘ throws keyword is used to declare an exception.
✘ You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
}
throw and throws Statements
✘ throws : to declare code causes an
exception
✗ Can throw more than one exception
✗ Causes the exception throw back to its
caller
✘ throw : create and throw new exception
object
Throw exception
Catch exception
31
throw Keywords
✘ throw is used to invoke an exception
explicitly.
33
finally block
✘ The finally block follows a try block or a
catch block. A finally block of code always
executes, irrespective of occurrence of an
Exception.
36
finally block
public class FinallyDemo{
catch(ArithmeticException e) {
System.out.println("I will execute if the exception is
generated");
}
finally {
System.out.println("I always execute at last");
}
}
}
try and catch – Code Example
public class ExceptionDemo2 {
public static void main (String args[]) {
try {
for (int i=0; i < 4; i++) {
System.out.println(house[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception : " + e.toString());
} finally {
System.out.println ("This is always executed");
}
} Gryfindor
} Slytherin
Ravenclaw
Exception :
java.lang.ArrayIndexOutOfBoundsException: 3
This is always executed
39
Exception Categories
1. Checked exceptions
• A checked exception is an exception that occurs at the compile
time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored at the time of compilation,
the Programmer should take care of (handle) these exceptions.
2. Unchecked exceptions
• An Unchecked exception is an exception that occurs at the time
of execution, these are also called as Runtime Exceptions, these
include programming bugs, such as logic errors or improper use of
an API. Runtime exceptions are ignored at the time of compilation.
RuntimeException
Java defines several exception classes inside the standard
package java.lang.
41
RuntimeException
NumberFormatException
• Invalid conversion of a string to a numeric
format.
ArrayIndexOutOfBoundsException
• Array index is out-of-bounds.
ArithmeticException
• Arithmetic error, such as divide-by-zero.
Common Exception
✘ ArithmeticException
✘ NullPointerException
✘ NegativeArraySizeException
✘ ArrayIndexOutOfBoundsException
✘ SecurityException
43
RuntimeException:
ArrayIndexOutOfBoundsException
class ArrayIndexOutOfBoundsExceptionDemo
{
public static void main(String args[])
{
int a[] = new int[10];
// Array has only 10 elements
a[11] = 9;
}
Output:
} Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at
ArrayIndexOutOfBoundsExceptionDemo.main(ArrayIndexOutOfBoundsExceptionDemo.java:7)
RuntimeException: ArithmeticException
class ArithmeticExceptionDemo
{
public static void main(String args[])
{
int num1 = 30, num2 = 0;
int output = num1 / num2;
System.out.println ("Result = " + output);
}
Output:
} Exception in thread "main" java.lang.ArithmeticException: / by zero
at
ArithmeticExceptionDemo.main(ArithmeticExceptionDemo.java:6)
RuntimeException: NumberFormatException
class NumberFormatExceptionDemo {
public static void main(String args[]){
int num = Integer.parseInt ("XYZ") ;
System.out.println(num);
}
Output:
} Exception in thread "main" java.lang.NumberFormatException: For input string:
"XYZ"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at
NumberFormatExceptionDemo.main(NumberFormatExceptionDemo.java:5)
Important Notes
✘ A catch clause cannot exist without a try
statement.
✘ It is not compulsory to have finally clauses when
ever a try/catch block is present.
✘ The try block cannot be present without either
catch clause or finally clause.
✘ Any code cannot be present in between the try,
catch, finally blocks.
exceptions are not always
caught but finally always
execute
48
Exercise
1. The exception class is in ____ package
[A] java.file
[B] java.io
[C] java.lang
[D] java.util