Exception Handling I
Exception Handling I
Exceptions in Java
Throwable class
Types of Exceptions
Missing semicolons.
Missing (or mismatch) of brackets in Classes and methods.
Misspelling of identifiers or keywords.
Missing double quotes in strings.
Use of undeclared variables.
Incomplete types in assignments / initialization.
Bad references to objects.
and many more . . .
Runtime Errors (Example)
import java.util.Scanner;
class Error {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
Output:
(1) 2 1 a divided by b : 2
(2) 9 2 a divided by b : 4
When an exception occurs within a method, it creates an object. This object is called the
Exception object.
The Exception object contains information about the exception, such as the name and
description of the exception and the state of the program when the exception occurred.
Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code. Exceptions thrown by Java relate to fundamental errors that violate
the rules of the Java language or the constraints of the Java execution environment.
Throwable Class
All exception and error types are
subclasses of the class Throwable,
which is the base class of the
exception 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
JVM to indicate errors having to do
with the run-time environment (JRE),
itself.
StackOverflowError is an example
of such an error.
Common methods in Throwable
class ThrowableExample {
String getMessage(): Returns the public static void main(String[] args) {
try {
detail message string of this throwable. int result = 10/0;
} catch (ArithmeticException e) {
System.out.println("Message: " +
Throwable getCause(): Returns
the cause of this throwable or null if the e.getMessage());
System.out.println("Cause: " +
cause is nonexistent or unknown.
e.getCause());
System.out.println("Exception: "
String toString(): Returns a + e.toString());
e.printStackTrace();
short description of this throwable. }
}
}
void printStackTrace(): Prints Output:
the throwable and its backtrace to the Message: / by zero
Cause: null
standard error stream.
Exception: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)
Types of Exception
The two main types of exceptions are:
Checked Exceptions (Compile-time Exceptions)
Unchecked Exceptions (Runtime Exceptions)
import java.io.FileReader;
import java.io.IOException;
class IOException_Example {
public static void main(String[] args) {
//Attempt to read from a file that doesn't exist
FileReader reader = new FileReader("nonexistentfile.txt");
reader.close();
}
}
Output:
Error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader reader = new FileReader("nonexistentfile.txt");
^
Main.java:8: Error: unreported exception IOException; must be caught or declared to be thrown
reader.close();
^
NumberFormatException
NumberFormatException is raised when a method could not convert a string into a numeric
format.
class NumberFormatException_Example {
public static void main(String[] args) {
int num = Integer.parseInt ("Student") ; //trying to assign a string
to an integer variable
System.out.println(num);
}
}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Student"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Main.main(Main.java:3)
ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException 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_Example {
public static void main(String args[]) {
int a[] = new int[5];
a[6] = 9; //accessing 7th element in an array of size 5
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for
length 5
at Main.main(Main.java:4)
StringIndexOutOfBoundsException
StringIndexOutOfBoundsException is thrown by String class methods to indicate that an
index is either negative or greater than the size of the string.
class StringIndexOutOfBound_Example {
public static void main(String args[]) {
String s = "This is like chipping "; //String length is 22
char ch = s.charAt(24); //accessing 25th element
System.out.println(ch);
}
}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 24
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:693)
at Main.main(Main.java:4)
NullPointerException
NullPointerException is thrown when referring to the members of a null object. Null
represents nothing.
class NullPointerException_Example {
public static void main(String args[]) {
String s = null; //null value
char ch = s.charAt(0); //accessing first element of the string
System.out.println(ch);
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:4)
Summary
Today, we learned about
• Throwable Class
• Types of Exceptions