JAVA unit 3
JAVA unit 3
What is Exception?
An Exception is an unwanted or unexpected event that occurs
during the execution of a program (i.e., at runtime) and disrupts the
normal flow of the program’s instructions.
int ans = n / m;
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).
Errors represent irrecoverable conditions such as
Error
Exception
Exception indicates conditions that a
An Error indicates a serious reasonable application might try to
problem that a reasonable catc
application should not try to catch.
Caused by conditions in the program
Caused by issues with the JVM or such as invalid input or logic errors.
hardware.
Ex: ArithmaticExcption,IoException,
Ex: StackOverFlow,
ArrayIndexOutOf Bounds Exception
OutOf MemoryError
Types of Java Exceptions
Java defines several types of exceptions that relate to its various
class libraries. Java also allows users to define their own
exceptions.
There are two types of exceptions
a) Userdefined Exceptions.
b) Built-in Exceptions
i)Checked Exceptions
ii)Unchecked Exceptions.
Types Of Exceptions
Built-in Exception
Build-in Exception are pre-defined exception classes provided by Java to
handle common errors during program execution.
1.1 Checked Exceptions or Compile-time Exceptions:
Checked exceptions are called compile-time exceptions because these exceptions
are checked at compile-time by the compiler.
Examples of Checked Exception are listed below:
ClassNotFoundException: Throws when the program tries to load a class at runtime
but the class is not found because its not present in the correct location or it is missing
from the project.
InterruptedException: Thrown when a thread is paused and another thread
interrupts it.
IOException: Throws when input/output operation fails.
InstantiationException: Thrown when the program tries to create an object of a class
but fails because the class is abstract, an interface, or has no default constructor.
SQLException: Throws when there’s an error with the database.
FileNotFoundException: Thrown when the program tries to open a file that doesn’t
Built-in Exception
1.2 Unchecked Exceptions or Run-time Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler
will not check these exceptions at compile time. In simple words, if a program throws
an unchecked exception, and even if we didn’t handle or declare it, the program
would not give a compilation error.
Examples of Unchecked Exception are listed below:
ArithmeticException: It is thrown when there’s an illegal math operation.
ClassCastException: It is thrown when you try to cast an object to a class it does
not belongs to.
NullPointerException: It is thrown when you try to use a null object (e.g. accessing
its methods or fields)
ArrayIndexOutOfBoundsException: It occurs when we try to access an array
element with an invalid index.
ArrayStoreException: It happens when you store an object of the wrong type in an
array.
IllegalThreadStateException: It is thrown when a thread operation is not allowed in
Methods to Print the Exception Information
Method Description
PrintStackTrace() Prints the full stack trace of the
exception, including the
name,message and location of the
error.
toString() Prints exception information in the
format of the name of the exception.
getMessage() Prints the description of the exception.
Try-Catch Block
Try-Catch Block
A try-catch block in Java is a mechanism to handle exception. The try block
contains code that might thrown an exception and the catch block is used to
handles the exceptions if it occurs.
try {
// Code that may throw an exception
}
catch (ExceptionType e) {
public static void main(String args[])
{
// Taking an empty string
String s = null;
// Getting length of a string
System.out.println(s.length());
}
}
How Programmer Handle an Exception?
Customized Exception Handling: Need for try-catch clause (Customized
Exception Handling)
Java exception handling uses five keywords:
try: Code that might cause an exception goes in the try block.
catch: If an exception occurs, it is caught using catch.
throw: We can throw exceptions manually with throw,
throws: methods must declare exceptions they can throw using throws.
finally: The finally block is used for code that must run after try, whether
an exception occurs or not.
class ArrayException
{
public static void main (String[] args)
{
int[] arr = new int[4];
try
{
int i = arr[4]
System.out.println("Inside try block");
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Exception caught in catch block");
}
finally
{
System.out.println("finally block executed");
}
System.out.println("Outside try-catch-finally clause");
}
Ex:Programme on try-catch block
import java.io.*;
class ExceptioExample{
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}
public class Exceptionhandling {
int n1=9,n2=0;
int result=0;
}
}
About ‘throw’ keyword in Java
The throw keyword in Java is used to explicitly throw an
exception from a method or any block of code.
We can throw either checked or unchecked exception. The
throw keyword is mainly used to throw custom exceptions.
Syntax:
throw Instance
Ex:
throw new ArithmeticException("/ by zero");
About ‘throws’ keyword in Java
throws: The throws keyword is used in method
signatures to declare the exceptions that a method
can throw, but doesn’t handle itself.
Example:
public void myMethod() throws IOException
{
// code that might throw an IOException
}
import java.io.*;
public class JavaExample {
public static void main(String args[]){
//method to read a file try
public static void readMyFile() throws {
FileNotFoundException { readMyFile();
}
FileReader file = catch (FileNotFoundException e)
new FileReader("C:\\Users\\myfile.txt"); {
BufferedReader text = new BufferedReader(file); System.out.println("File Not Found: "+e);
System.out.println(text); }
}
//if file doesn't exist throw a checked exception }
if(text == null) {
throw new FileNotFoundException();
}
}
Chained exceptions
Chained exceptions allow you to associate one exception with another, allowing the underlying
reason for an exception to be tracked.
Example:
try {
throw new IOException("Top-level exception");
} catch (IOException e) {
throw new RuntimeException("Wrapper exception", e);
}
You can retrieve the original cause using getCause().
Customized Exceptions:
Customized exceptions is nothing but creating your own exception using subclass.That is
by extending the Exception or RuntimeException class.
In Java, you can have multiple catch blocks to handle different types of exceptions that may
arise in a try block. This allows you to handle each exception type in a specific way.
try {
// Some code that may throw an exception
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " + e);
}
catch (Exception e) {
System.out.println("General Exception caught: " + e);
}
Note:The most specific exceptions should be caught first, followed by more general ones.
Nested try statements:
Java allows you to nest try statements, which means you can have one try block inside another
try block. This is useful when a specific block of code might throw multiple exceptions at different
levels.
Example:
try {
// Outer try block
try {
// Inner try block
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException in inner try: " + e);
}
} catch (Exception e) {
System.out.println("General exception in outer try: " + e);
}