0% found this document useful (0 votes)
3 views

Lecture 11_ Exception

Uploaded by

sheikhshoumik64
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture 11_ Exception

Uploaded by

sheikhshoumik64
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Exception Handling

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.

Differences Between Exceptions and Errors:


Exceptions:
● Handled using try-catch blocks.
● Allow for graceful recovery.
● Examples include ArithmeticException for division by zero or
ArrayIndexOutOfBoundsException for accessing an index out of bounds.

Errors:
● Often fatal and lead to program termination.
● Examples include OutOfMemoryError or StackOverflowError.

4
Introduction to Exceptions

ArithmeticException: It is thrown when an exceptional condition has


occurred in an arithmetic operation.
class ArithmeticException_Demo {
public static void main(String args[]) {
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}}}
5
Introduction to Exceptions
ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or equal to the
size of the array.

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.

public class ClassNotFoundException_Demo {


public static void main(String[] args) {
try{
Class.forName("Class1"); // Class1 is not defined
}
catch(ClassNotFoundException e){
System.out.println(e);
System.out.println("Class 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());

// Check if there is an IO exception


System.out.println("Exception Output: " + scan.ioException());
scan.close(); } }

9
Introduction to Exceptions
NoSuchMethodException: It is thrown when accessing a method that is not found.

public class NoSuchElementException_Demo {


public static void main(String[] args) {
Set exampleleSet = new HashSet();
Hashtable exampleTable = new Hashtable();
exampleleSet.iterator().next();
//accessing Set
exampleTable.elements().nextElement();
//accessing Hashtable
// This throws a NoSuchElementException as there are
// no elements in Set and HashTable and we are
// trying to access elements
}}
10
Introduction to Exceptions
NullPointerException: This exception is raised when referring to the
members of a null object. Null represents nothing.

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:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10


at Main.main(Main.java:4)

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:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10


at Main.main(Main.java:4)

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.

public class Main {


public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);}
catch (Exception e) {
System.out.println("Something went wrong.");}
finally {
System.out.println("The 'try catch' is finished.");
}}}
The output will be: Something went wrong.
The 'try catch' is finished.

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"); }}

Output: Exception caught in Catch block


Outside try-catch clause
21
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

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

Throw & Throws Example:


public class TestThrowAndThrows {
// defining a user-defined method
// which throws ArithmeticException
Public static void method() throws ArithmeticException {
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[]) {
try {
method();
}
catch(ArithmeticException e) {
System.out.println("caught in main() method");
} } }

27
Exceptions Handling

Throw & Throws Example:


public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}

28
Exceptions Handling

Customized Exception Example: // Example.java


// CustomException.java public class Example {
public class CustomException extends Exception { public static void main(String[] args) {
try {
validateInput(5);
// Constructors
validateInput(-1); // This will throw CustomException
public CustomException() { } catch (CustomException e) {
super(); System.err.println("Caught a custom exception: " +
} e.getMessage());
public CustomException(String message) { }
super(message); }
}
public static void validateInput(int value) throws
public CustomException(String message, Throwable
cause) { CustomException {
super(message, cause); if (value < 0) {
throw new CustomException("Input must be
}
non-negative");
} }
// Business logic for valid input
}}

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

You might also like