Week 11 Exception
Week 11 Exception
Department of CSE
Course Title: Object Oriented Programming
Course Code: CSE 061 1203
Week - 11
Class – 01
1|Page
3. Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
5. Exception Hierarchy
• All exception and error types are subclasses of the class Throwable, which
is the base class of the hierarchy.
• One branch is headed by Exception.
• This class is used for exceptional conditions that user programs should catch.
• NullPointerException is an example of such an exception.
• Another branch, Error is used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.
2|Page
Java Exception Hierarchy
6. Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries.
Java also allows users to define their own exceptions.
3|Page
Exceptions can be categorized in two ways:
1. Built-in Exceptions
➢ Checked Exception
➢ Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
Output:
java.lang.Arithmetic Exception:/by zero
at GFG.main(File.java:10)
5|Page
2. toString()
The toString() method prints exception information in the format of the Name of
the exception: description of the exception.
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}
}
}
6|Page
3. getMessage()
The getMessage() method prints only the description of the exception.
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}
Output: / by zero
7|Page
Class – 03
8|Page
// Now this statement will cause an exception
int i = arr[4];
Output
Output explanation: In the above example, an array is defined with size i.e. you
can access elements only from index 0 to 3. But you trying to access the elements
at index 4(by mistake) that’s why it is throwing an exception. In this case, JVM
terminates the program abnormally. The statement System.out.println(“Hi, I want
to execute”); will never execute. To execute it, we must handle the exception using
try-catch. Hence to continue the normal flow of the program, we need a try-catch
clause.
9|Page
// exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally { // block of code to be executed after try block ends
}
11 | P a g e