0% found this document useful (0 votes)
116 views29 pages

Exception Handling in Java

Exception handling in Java allows programs to intercept runtime errors, take corrective actions, and continue running. Exceptions can be checked exceptions that must be handled, unchecked exceptions that do not require handling, or errors outside the program's control. Java provides try-catch blocks to handle exceptions, with multiple catch blocks ordered from specific to general exceptions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
116 views29 pages

Exception Handling in Java

Exception handling in Java allows programs to intercept runtime errors, take corrective actions, and continue running. Exceptions can be checked exceptions that must be handled, unchecked exceptions that do not require handling, or errors outside the program's control. Java provides try-catch blocks to handle exceptions, with multiple catch blocks ordered from specific to general exceptions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

Exception Handling in Java

Dr. Kuppusamy .P
Associate Professor / SCOPE
Exception
• An exception is an abnormal event occurs during the execution of the program,
that interrupts the normal flow of the program‘s instruction.
• Exceptions are generated when a recognize the condition (usually an error
condition) during the execution of a method.
• Exception can be generated by Java-runtime system or they can be manually
generated by code.
Exception handling
• The ability of a program to intercept run-time errors, take corrective measures and
continue execution to maintain the normal flow of the application.
• An exceptions occur at various situations:
• Attempting to access a file that does not exist
• Inserting an element into an array at a position that is not in its bounds
• Performing some mathematical operation that is not permitted
• Declaring an array using negative values
• Resource allocation Error
• Problems in Network connectivity.
Dr. Kuppusamy P
Exception Hierarchy

Dr. Kuppusamy P
Exception Hierarchy

Dr. Kuppusamy P
Exceptions
Two types of exceptions:
Compile time exceptions
✓ Compiler time error means Java compiler identify the syntax error at the time of
compilation.
✓ Compiler does not create .class file without successful compilation.
✓ Missing braces
✓ Missing semicolon
✓ Missing double quote in string
✓ = instead of == operator, and etc.
Run time exceptions
• Program may compile successfully several times and compiler creates the class file of the
program.
• But when the time of running the program, it shows the error is called run time error.
The common problems are:
• Divide by zero
• Conversion of invalid string to number
• access the element that is out of bound of an array
• Passing the parameters with invalid range.
Dr. Kuppusamy P
Checked Exception
• This exception is checked (notified) by the compiler at compilation-time (compile
time exceptions). These exceptions cannot simply be ignored, the programmer
should handle these exceptions.
Ex.
• User writes FileReader class in the program to read data from a file. If the file
doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
import java.io.File;
import java.io.FileReader;
public class File_Demo {
public static void main(String args[]) {
File file = new File(“D:\\file.txt");
FileReader fr = new FileReader(file);
} }

Dr. Kuppusamy P
UnChecked Exception
• This exception occurs at the time of execution called as Runtime Exceptions such
as logic errors or improper use of an API.
• Runtime exceptions are ignored at the time of compilation.
E.g.
• If user declared an array of size 3, and trying to call the 4th element of the array
then an ArrayIndexOutOfBoundsExceptionexception occurs.
public class Uncheck_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3};
System.out.println(num[4]);
}
}

Dr. Kuppusamy P
StringIndexoutofbounds Exception Example
public class StringIndex {
public static void main(String[] args) {
String s = "Welcome to the Classroom";
System.out.println("String Length is : "+s.length());
for(int j=0; j<s.length(); j++) {
System.out.print(" "+s.charAt(j));
}
System.out.println("Access the 50th alphabet:"+s.charAt(50));
}
}

Dr. Kuppusamy P
IllegalArgumentException Example

public class ExIllegalarg {


static int v = 10;
public static int getValue(String s) {
if(s == null) {
throw new IllegalArgumentException("Arguments can not be null");
}
return v;
}
public static void main(String[] args) {
String s = null;
try {
System.out.println(getValue(s));
}catch (IllegalArgumentException e) {
System.out.println(" IllegalArgumentException Caught");
}}
}
Dr. Kuppusamy P
NullPointerException Example 1

public class Main {


public static void main(String[] args) {
Object ref = null;
ref.toString(); // throw a NullPointerException
}
}

Dr. Kuppusamy P
NullPointerException Example 2

class Sample {
public static Sample set_Value() { //returns a null object
return null;
} public void print(String s) {
System.out.println(s);
}
}
class Main{
public static void main(String[] args) {
Sample x = Sample.set_Value(); //create a new object (null object)
x.print("Hi!"); //invoke method using null object
}
}

Dr. Kuppusamy P
Errors
✓ Error is not considered as an Exception.
✓ Errors are problems that arise beyond the control of the programmer.
✓ Occurs due to the lack of system resources and our application should not catch these types
of problem.
✓ Errors mostly occur at runtime. So, they belong to an unchecked type.
Ex :
✓ Stack Overflow Error, OutofMemory Error, System Crash Error
✓ It is irrecoverable
✓ Errors are also ignored by the compiler.
public class ErrorExample {
public static void main(String[] args){
recursiveMethod(10);
}
public static void recursiveMethod(int i){
while(i!=0){
i=i+1;
Error:
recursiveMethod(i); java.lang.StackOverflowError
}
} } Dr. Kuppusamy P
Exception Handling
Different approaches to handle exceptions in Java.
• try...catch block
• finally block
• throw and throws keyword.
try…catch block
• The try statement allows to define a block of code to be tested for errors while it is
being executed.
• The catch statement allows to define a block of code to be executed, if an error
occurs in the try block.
try {
// Block of code to be tested
}
catch(Exception e) {
// Block of code to handle errors
}
Dr. Kuppusamy P
try .. catch
• If user declared an array of size 3, and trying to call the 4th element of the array
then an ArrayIndexOutOfBoundsExceptionexception occurs.
public class Uncheck_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3};
System.out.println(num[4]);
}}

public class Uncheck_Demo {


public static void main(String[ ] args) {
try {
int[] num = {1, 2, 3};
System.out.println(num[4]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
} Dr. Kuppusamy P
try…catch block
public class Main
{
public static void main(String ar[])
{
try
{
int x = 30 / 0;
} catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
}

Dr. Kuppusamy P
Multiple catch block
• A single block of code can raise more than one exception.
• So, use two or more catch clauses for catching a different type of exceptions.
• At a time, only one exception occurs and at a time only one catch block is
executed.
• All catch blocks must be ordered from most specific to most general, i.e., catch for
ArithmeticException must come before catch for Exception.
• When using multiple catch statements, it is important to remember that subclasses
exception must come before any of their superclass’s exception.
• Because a catch statement that uses a superclass will catch exceptions of that type
as well as exceptions of its subclasses.
• Thus, a subclass exception would never be reached if it came after its superclass
that manifests as an unreachable code error.
try{
//block of statements
}catch(Exception handler class subclass ){
} catch(Exception handler super class){
Dr. Kuppusamy P
}
Multiple catch block

Dr. Kuppusamy P
Multiple catch block
public class Main {
public static void main(String ar[])
{
try{
int len=ar.length;
System.out.println(34/len);
System.out.println(ar[5]);
}
catch(ArithmeticException e){
System.out.println(“Division by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("array index error");
}
}} Dr. Kuppusamy P
catch blocks to be in order from specific to
general catch block
class Arith{
int array[]={5,10,15,20};
int num1 = 100;
int num2 =20;
public void multiCatch(){
try{
//java.lang.ArithmeticException here if num2 = 0.
System.out.println(num1/num2);
System.out.println("4th element of given array = " + array[3]);
//ArrayIndexOutOfBoundsException here.
System.out.println("5th element of given array = " + array[4]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
Dr. Kuppusamy P
catch blocks to be in order from specific to general
catch block
catch(ArithmeticException e){ //catch ArithmeticException here.
System.out.println(e);
}catch(Exception e){ //catch general exceptions here.
System.out.println(e);
}
System.out.println("Remaining code after exception handling.");
}
}
public class ExceEx1 {
public static void main(String args[]){
Arith obj = new Arith();
obj.multiCatch();
}
}
Dr. Kuppusamy P
catch blocks NOT in order from specific to
general catch block
class Arith{
int array[]={5,10,15,20};
int num1 = 100;
int num2 =20;
public void multiCatch(){
try{
//java.lang.ArithmeticException here if num2 = 0.
System.out.println(num1/num2);
System.out.println("4th element of given array = " + array[3]);

//ArrayIndexOutOfBoundsException here.
System.out.println("5th element of given array = " + array[4]);
}catch(Exception e){ //catch general exceptions here.
System.out.println(e);
} Dr. Kuppusamy P
catch blocks NOT in order from specific to general
catch block
catch(ArrayIndexOutOfBoundsException e){ //Compile time error here.
System.out.println(e);
}catch(ArithmeticException e){ //catch ArithmeticException here.
System.out.println(e);
}
System.out.println("Remaining code after exception handling.");
}
}
public class ExceEx {
public static void main(String args[]){
Arith obj = new Arith();
obj.multiCatch();
}
}
Dr. Kuppusamy P
Nested try Statements
• The try statement can be nested.
• If an inner try statement does not have a catch handler for a particular exception,
the outer block’s catch handler will handle the exception.
• This continues until one of the catch statement succeeds, or until all the nested try
statements are exhausted .
• If no catch statement matches, then the Java runtime system will handle the
exception.
try{ //block of statements
try{
//block of statements
}catch(Exception handler class){
}
}catch(Exception handler class){
}

Dr. Kuppusamy P
Nested Try statements
public class NestTry {
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println(“Divide by 0");
int x =20/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
Dr. Kuppusamy P
Nested Try statements
//inner try block 2
try{
int y[]=new int[10];
//assigning the value out of array bounds
y[25]=40;
} //catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}

Dr. Kuppusamy P
Nested Try statements
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}

Dr. Kuppusamy P
Finally clause in java
• The finally block follows a try block or a catch block.
• A finally block of code always executes, irrespective of occurrence of an
Exception.
• A try block can have one or more catch block associated with it, but only one
finally block can be associates with it.
Why finally is needed?
• The finally keyword is used to execute code without consideration of the
occurrence of an exception or not.
• Eg: freeing the resources i.e., closing the file, database connectivity, etc.,
try{

//block of statements

} catch(){

}finally{

}
Dr. Kuppusamy P
Finally clause in java
public class ExcepTest {
public static void main(String args[]) {
int x[] = new int[2];
try {
System.out.println("Access element five :" + x[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
x[0] = 15;
System.out.println("First element value: " + x[0]);
System.out.println("The finally statement is executed");
}
}
}

Dr. Kuppusamy P
References

• Herbert Schildt, “Java: The Complete Reference”, McGraw-Hill Education, Tenth


edition, 2017.
• Joyce Farrell, “Java Programming”, Cengage Learning, Eighth Edition, 2016.
• Mark Lassoff, “Java Programming for Beginners”, Pack Publishing, 2017

Dr. Kuppusamy P

You might also like