Lecture 11_ Exception
Lecture 11_ Exception
Lecturer’s Contents
• Background details of Exception
• Try
• Catch
• Finally
2
Introduction to Exceptions
Types of Errors:
1. Syntax Errors: Syntax errors occur when the code violates the rules of the programming language.
These errors are detected by the compiler or interpreter during the code compilation phase.
public static void main(String[] args) {
System.out.println("Hello, World"; }}
2. Runtime Errors: Runtime errors occur during the execution of the program. They are often caused by
unexpected conditions that arise while the program is running.
int result = 10 / 0 //Runtime Error (division by zero)
3. Logical Errors: Logical errors occur when the code is syntactically correct but does not produce the
expected output due to flawed logic.
public class Example {
public static void main(String[] args) {
int total = 0; // Logical Error (incorrect algorithm)
for (int i = 0; i <= 5; i++) {
total += i;}
System.out.println("Sum of first 5 numbers: " + total);}}
3
Introduction to Exceptions
Definition and Purpose of Exceptions:
In Java, an exception is an event that occurs during the execution of a program,
disrupting the normal flow of the program's instructions. Exceptions provide a
mechanism to handle errors and exceptional situations in a controlled manner.
Errors:
● Often fatal and lead to program termination.
● Examples include OutOfMemoryError or StackOverflowError.
4
Introduction to Exceptions
class ArrayIndexOutOfBound_Demo {
public static void main(String args[]) {
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}}}
6
Introduction to Exceptions
ClassNotFoundException: This Exception is raised when we try to access a
class whose definition is not found.
7
Introduction to Exceptions
FileNotFoundException: This Exception is raised when a file is not accessible or does not
open.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[]) {
try {
// Following file does not exist
File file = new File("E://file.txt");
FileReader fr = new FileReader(file); }
catch (FileNotFoundException e) {
System.out.println("File does not exist"); }}}
8
Introduction to Exceptions
IOException: It is thrown when an input-output operation failed or interrupted.
class IOException_Demo {
public static void main(String[] args) {
// Create a new scanner with the specified String
// Object
Scanner scan = new Scanner("Hello Geek!");
// Print the line
System.out.println("" + scan.nextLine());
9
Introduction to Exceptions
NoSuchMethodException: It is thrown when accessing a method that is not found.
class NullPointer_Demo {
public static void main(String args[]) {
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}}}
11
Introduction to Exceptions
NumberFormatException: This exception is raised when a method could not
convert a string into a numeric format.
class NumberFormat_Demo {
public static void main(String args[]) {
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num); }
catch(NumberFormatException e) {
System.out.println("Number format exception");
}}}
12
Introduction to Exceptions
StringIndexOutOfBoundsException: It is thrown by String class methods to
indicate that an index is either negative or greater than the size of the string.
class StringIndexOutOfBound_Demo {
public static void main(String args[]) {
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c); }
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}}}
13
Introduction to Exceptions
IllegalArgumentException : This exception will throw the error or error statement when the method
receives an argument which is not accurately fit to the given relation or condition. It comes under
the unchecked exception.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void print(int a) {
if(a>=18){
System.out.println("Eligible for Voting");
}
else{
throw new IllegalArgumentException("Not Eligible for Voting");
} }
public static void main(String[] args) {
GFG.print(14); } }
14
Introduction to Exceptions
IllegalStateException : This exception will throw an error or error message when the method is not accessed
for the particular operation in the application. It comes under the unchecked exception.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void print(int a,int b) {
System.out.println("Addition of Positive Integers :"+(a+b));
}
public static void main(String[] args) {
int n1=7;
int n2=-3;
if(n1>=0 && n2>=0) {
GFG.print(n1,n2);
}
else{
throw new IllegalStateException("Either one or two numbers are not Positive Integer");
}}}
15
Exceptions Handling
Try:
The try statement allows you to define a block of code to be tested for errors while it is being executed.
Catch:
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. We
can write multiple catch block at a single class.
try {
//Block of code to try/monitor
}
catch(Exception e) {
//Block of code to handle errors
}
catch(Exception e1) {
//Block of code to handle errors
}
16
Exceptions Handling
Example:
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
This code will generate an error, because myNumbers[10] does not exist.
The output will be something like this:
17
Exceptions Handling
Example:
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
This code will generate an error, because myNumbers[10] does not exist.
The output will be something like this:
18
Exceptions Handling
Solution:
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Something went wrong.");
}
}}
The output will be: Something went wrong.
19
Exceptions Handling
Finally:
The finally statement lets you execute code, after try...catch, regardless of the result.
20
Exceptions Handling
Example:
class GFG {
public static void main (String[] args) {
// array of size 4.
int[] arr = new int[4];
try{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");}
catch(ArrayIndexOutOfBoundsException exp){
System.out.println("Exception caught in Catch block");}
// rest program will be executed
System.out.println("Outside try-catch clause"); }}
Example:
class GFG{
public static void main (String[] args) {
// array of size 4.
int[] arr = new int[4];
try{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Exception caught in catch block");}
finally{
System.out.println("finally block executed");}
// rest program will be executed
System.out.println("Outside try-catch-finally clause");}}
Output: Exception caught in catch block
finally block executed
Outside try-catch-finally clause
22
Exceptions Handling
Example:
class GFG{
public static void main (String[] args) {
// array of size 4.
int[] arr = new int[4];
try{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Exception caught in catch block");}
finally{
System.out.println("finally block executed");}
// rest program will be executed
System.out.println("Outside try-catch-finally clause");}}
Output: Exception caught in catch block
finally block executed
Outside try-catch-finally clause
23
Exceptions Handling
Throw:
• The throw keyword is used to create a custom error.
• Java throw keyword is used throw an exception explicitly in the code, inside the function or the
block of code.
• The throw keyword is followed by an instance of Exception to be thrown.
• Throw is used within the method
• We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions
Throws:
• Java throws keyword is used in the method signature to declare an exception which might be
thrown by the function while the execution of the code.
• The throws keyword is followed by class names of Exceptions to be thrown.
• throws is used with the method signature.
• We can declare multiple exceptions using throws keyword that can be thrown by the method. For
example, main() throws IOException, SQLException.
24
Exceptions Handling
Throw Example:
public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
} }
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
} }
25
Exceptions Handling
Throws Example:
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div; }
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
} }
26
Exceptions Handling
27
Exceptions Handling
28
Exceptions Handling
29
Exceptions Handling
// class that uses custom exception InvalidAgeException
*Let's see a simple example of Java custom
exception. In the following code, constructor of public class TestCustomException1 {
InvalidAgeException takes a string as an // method to check the age
argument. This string is passed to constructor of static void validate (int age) throws InvalidAgeException{
parent class Exception using the super() method. if(age < 18){
Also the constructor of Exception class can be
called without using a parameter and calling // throw an object of user defined exception
super() method is not mandatory. throw new InvalidAgeException("age is not valid to vote");
}
else {
class InvalidAgeException extends Exception {
System.out.println("welcome to vote");
public InvalidAgeException (String str) {
} }
// calling the constructor of parent // main method
Exception
public static void main(String args[]) {
super(str); try {
} // calling the method
} validate(13);
}
catch (InvalidAgeException ex) {
System.out.println("Caught the exception");
// printing the message from InvalidAgeException object
System.out.println("Exception occured: " + ex); }
System.out.println("rest of the code...");
} } 30
Exceptions Handling
Examples:
package Course;
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[1]);
try {
int x=5;
int y=0;
System.out.println(myNumbers[10]);
System.out.println(x/y);
}
catch ( ArrayIndexOutOfBoundsException e) {
System.out.println("Something went wrong1.");}
catch (ArithmeticException e1) {
System.out.println("Something went wrong2.");}
finally{ Output:
System.out.println("Hello"); 2
System.out.println(myNumbers[0]); Something went wrong1.
}}}
Hello
1
31