Nothing Special   »   [go: up one dir, main page]

EXCEPTION IN JAVA

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

TOPIC TWO

What is an Exception?
An exception is an “unwanted or unexpected event”, which occurs during the execution of the
program i.e, at run-time, that disrupts the normal flow of the program’s instructions. When an
exception occurs, the execution of the program gets terminated.
An exception is an unexpected event that occurs during program execution. It affects the flow of
the program instructions which can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file
Java Exception hierarchy
Here is a simplified diagram of the exception hierarchy in Java.

Errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle errors.
Exceptions
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called the
exception object.
It contains information about the exception such as the name and description of the exception
and state of the program when the exception occurred.

Types of Java Exception


Runtime Exception
A runtime exception happens due to a programming error. They are also known as unchecked
exceptions.
These exceptions are not checked at compile-time but run-time. Some of the common runtime
exceptions are:
 Improper use of an API - IllegalArgumentException
 Null pointer access (missing the initialization of a variable) - NullPointerException
 Out-of-bounds array access - ArrayIndexOutOfBoundsException
 Dividing a number by 0 - ArithmeticException
2. IOException
An IOException is also known as a checked exception. They are checked by the compiler at the
compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
 Trying to open a file that doesn’t exist results in FileNotFoundException
 Trying to read past the end of a file
Java Exception Handling
Exceptions abnormally terminate the execution of a program.
This is why it is important to handle exceptions. Here's a list of different approaches to handle
exceptions in Java.
 try...catch block
 finally block
 throw and throws keyword
1. try --The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
2. catch: The catch block is used to handle the uncertain condition of a try block. A try
block is always followed by a catch block, which handles the exception that occurs in the
associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
3. throw: The throw keyword is used to transfer control from the try block to the catch block.
4. throws: The throws keyword is used for exception handling without try & catch block. It
specifies the exceptions that a method can throw to the caller and does not handle itself.
5. finally: It is executed after the catch block. We use it to put some common code (to be
executed irrespective of whether an exception has occurred or not ) when there are multiple catch
blocks.

Java try...catch block


The try-catch block is used to handle exceptions in Java. Here's the syntax of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}
Example
class Main {
public static void main(String[] args) {

try {

// code that generate exception


int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output
ArithmeticException => / by zero

Example 2
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}

catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}

}
}

Output
Exception caught:Division by zero

Java finally block


In Java, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.

The basic syntax of finally block is:


try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
Example 1

class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}

Output
ArithmeticException => / by zero
This is the finally block
Java throw and throws keyword
The Java throw keyword is used to explicitly throw a single exception.
When we throw an exception, the flow of the program moves from the try block to the catch
block.
Example: Exception handling using Java throw
class Main {
public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by
0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)

You might also like