Core Java
Lesson 8—Exception Handling
© Simplilearn. All rights reserved.
Learning Objectives
At the end of this lesson, you should be able to:
Differentiate between the types of exceptions
Create a try-catch block and determine how exceptions alter normal
program flow
Describe the advantages of exception handling
Create and invoke a method that throws an exception
Apply “finally” block
Recognize common exception classes
Exception Handling
Topic 1—Types of Exceptions
Types of Exceptions
Asynchronous Exceptions Synchronous Exceptions
Deal with hardware problems and external Deal with programmatic run-time errors
problems
Types:
• Mouse failure • Checked exceptions
• Keyboard, motherboard failures • Unchecked exceptions
• Memory problems
• Power failures
Java.lang.Error is a super class of all
asynchronous Exceptions
Types of Synchronous Exceptions
Checked exceptions
The ones that are expected to be handled by the programmer and arise from external conditions
during compile time
Examples: “requested file not found,” “network failure”
Unchecked exceptions
The ones that arise from conditions that represent bugs during execution time, or situations that are
considered difficult to handle
Example: “runtime exceptions are attempting to access beyond the end of an array”
Difference between Error Class and Exception Class
Errors Exceptions
Errors in Java are of type java.lang.Error. Exceptions in Java are of type java.lang.Exception.
All errors in Java are of unchecked type. Exceptions may be checked as well as unchecked.
Checked exceptions are known to compiler, whereas
Errors happen at run-time. They will not be known to the
unchecked exceptions are not known to compiler because
compiler.
they occur at run-time.
You can recover from exceptions by handling them
It is impossible to recover from errors.
through try-catch blocks.
Errors are mostly caused by the environment in which the
Exceptions are mainly caused by the application itself.
application is running.
Examples :
Examples : Checked Exceptions: SQLException, IOException
java.lang.StackOverflowError, java.lang.OutOfMemoryError Unchecked Exceptions: ArrayIndexOutOfBoundException,
ClassCastException, NullPointerException
Hierarchy of Exception
ArithmeticException
ClassNotfoundException
ArrayStoreException
CloneNotSupportedException
ClassCastException
Object IllegalAccessException
IllegalThreadStateException
IllegalArgumentException
Throwable InstantiationException
NumberFormatException
IllegalMonitorStateException
InterruptedException
Exception ArrayIndexOutOfBoundsException
IndexOutOfBoundsExceptions
NoSuchMethodException
StringIndexOutOfBoundsException
NegativeArraySizeException
RutimeException
NullPointerException
SecurityException
Exception Example
public class AddArguments {
public static void main(String agrs[]) {
int sum = 0;
for (int i=0; I < args.length; i++) {
sum += Integer.parseInt (args[i]);
}
System.out.println(“Sum = ” + sum);
}
}
If we add arguments, then it will throw exceptions
java AddArguments 1 two 3.04
Exception Handling
Topic 2—try-catch Statement
try-catch Statement
When you write a Java program, you come across exceptions. In order to catch these exceptions,
you have try-catch statement.
Example of a program that handles exception:
Public class AddArguments2
{
public static void main(String args[]) {
try {
int sum = 0;
for (int i=0; i < args.length; i++) {
sum += Integer.parseInt (args [i]);
}
System.out.println(“Sum = “ +sum);
} catch (NumberFormatException nfe) {
system.err.println(“One of the command-line” + “arguments is not an integer.”);
}
}
}
try-catch Statement (Contd.)
This program captures the exception and then quits with an error message:
Java AddArguments2 1 two 3.0 4
One of the command-line arguments is not an integer.
Exception Handling
Topic 3—Advantages of Exception Handling
Advantages of Exception Handling
Separating Error-Handling Code from "Regular" Code:
Exceptions provide the means to separate the details of something out of the ordinary from the main logic
of a program. In traditional programming, error detection, reporting, and handling often led to confusing
spaghetti code.
Propagating Errors up the Call Stack
Exceptions have the ability to propagate error reporting up the call stack of methods.
Grouping and Differentiating Error Types
Because all Exceptions thrown within a program are objects, the grouping or categorizing of Exceptions is a
natural outcome of the class hierarchy. IOException and its descendants is an example of a group of
related Exception classes in the Java platform. It is defined in java.io. IOException is the most general and
represents any type of error that can occur when performing I/O. Its descendants represent more specific
errors.
Exception Handling
Topic 4—throws Statement
throws Keyword
throws keyword is used to declare an exception.
It provides information to the programmer that an exception may occur, which helps programmer to
provide the exception handling code to maintain normal flow.
Syntax for throws exception:
return_type method_name()throws exception_class_name
{
//method code
}
throw Keyword
throw keyword is used to invoke an exception
Differences between throws and throw Keyword:
throw throws
Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception.
Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You can declare multiple exceptions, for example,
You cannot throw multiple exceptions.
public void method()throws IOException and SQLException.
throws Keyword—Example
The following example shows how Java throws keyword checks exceptions:
import java.io.IOException;
class Testthrows1
{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception corrected");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println(“Program works fine...");
} Output: Exception corrected
} Program works fine...
Exception Handling
Topic 5—finally block
finally Block
finally block is used to execute important code such Program code
as closing connection, stream, and so on.
It is always executed, regardless of whether no yes
Exception
exception is handled or not. occurred?
It follows try or catch block.
no yes
Exception
handled?
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);} Block is finally
finally{System.out.println("finally block is executed"); executed
}}
Difference between Error Class and Exception Class
Final finally finalize
Final is used to apply restrictions on Finally is used to place important Finalize is used to perform clean up
class, method, and variable. Final class code. It will be executed whether processing just before object is
can't be inherited, final method can't exception is handled or not. garbage collected.
be overridden, and final variable value
can't be changed.
Final is a keyword. Finally is a block. Finalize is a method.
Example for final keyword Example for finally keyword
class FinalExample class FinallyExample
{ {
public static void main(String[] args){ public static void main(String[] args){
final int x=100; try{
x=200;//Compile Time Error int x=300;
}} }catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
Exception Handling
Topic 6—Exception Classes
Creating User-defined Exceptions
You can create your own exception. This exception will be known as custom or user-defined exception.
Creating Custom Exception: Use of Custom Exception:
class InvalidAgeException extends Exception class TestCustomException1
{ {
InvalidAgeException(String s){ static void validate(int age)throws InvalidAgeException{
super(s); if(age<18)
} throw new InvalidAgeException("not valid");
} else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured:"+m);}
System.out.println(“Code is executing");
}
Output:
} Exception occurred: InvalidAgeException:not valid
Code is executing
NullPointerException
NullPointerException is one of the common exception classes.
It is thrown when an application attempts to use null in a case where an object is required,
such as:
Calling the instance method of a null object
Accessing or modifying the field of a null object
Taking the length of null as if it were an array
Accessing or modifying the slots of null as if it were an array
Throwing null as if it were a Throwable value
Example of NullPointerException:
Object obj = null;
obj.toString(); // This statement will throw a NullPointerException
ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException occurs when an integer is divided by zero
Example of ArrayIndexOutOfBoundsException:
class Exception2
{
public static void main(String args[])
{
try{
int a[]=new int[10]; //Array has only 10 elements
a[15] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output:
ArrayIndexOutOfBounds
java.lang.ClassCastException
java.lang.ClassCastException occurs when you try to cast an object stored in a reference variable
into another object in run-time
Example of ClassCastException:
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
Key Takeaways
In Java-synchronous exceptions, there are two types of exceptions, namely,
checked exceptions and unchecked exceptions
When you write a Java program, you come across exceptions. In order to catch
those exceptions, you can use try-catch statement.
Exception Handling has many advantages.
To throw an exception, use a throws statement and provide it with an exception
object.
Some of the common exception classes are NullPointerException,
ArithmeticException, ClassCastException, and ArrayIndexOutOfBoundsException.
Quiz
QUIZ
Which of these are Checked Exceptions?
1
a. ArithmeticException
b. ClassCastException
c. FileNotFoundException
d. ClassNotFoundException
QUIZ
Which of these are Checked Exceptions?
1
a. ArithmeticException
b. ClassCastException
c. FileNotFoundException
d. ClassNotFoundException
The correct answer is c and d.
Checked Exceptions are exceptions that are thrown by the compiler. The programmer must handle
them. Options “c” and “d” are checked exceptions.
QUIZ
Which of these classes are subclasses of RunTimeException class?
2
a. NullPointerException
b. ArithmeticException
c. ArrayIndexOutOfBoundsException
d. All of the above
QUIZ
Which of these classes are subclasses of RunTimeException class?
2
a. NullPointerException
b. ArithmeticException
c. ArrayIndexOutOfBoundsException
d. All of the above
The correct answer is d. All of the above
NullPointerException, ArithmeticException, and ArrayIndexOutOfBoundsException are subclasses
of RunTimeException class.
Thank You