0% found this document useful (0 votes)
6 views9 pages

Untitled Document

The document discusses exception handling in Java, which is a mechanism to manage runtime errors and maintain the normal flow of applications. It categorizes exceptions into checked exceptions, unchecked exceptions, and errors, providing examples for each type. The document also includes code snippets demonstrating how to handle various exceptions, such as FileNotFoundException, IOException, and ArithmeticException.

Uploaded by

middenchopra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views9 pages

Untitled Document

The document discusses exception handling in Java, which is a mechanism to manage runtime errors and maintain the normal flow of applications. It categorizes exceptions into checked exceptions, unchecked exceptions, and errors, providing examples for each type. The document also includes code snippets demonstrating how to handle various exceptions, such as FileNotFoundException, IOException, and ArithmeticException.

Uploaded by

middenchopra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

The Exception Handling in Java is one of the powerful mechanism to handle the

runtime errors so that the normal flow of the application can be maintained.

An exception is an event that occurs during the execution of a program that


disrupts the normal flow of instructions. These exceptions can occur for various
reasons, such as invalid user input, file not found, or division by zero. When an
exception occurs, it is typically represented by an object of a subclass of the
java.lang.Exception class.

Exception handling is a technique of processing problems that occur during the


execution of a program. Using exception handling, we can test code and avoid it
from exiting abruptly.

exceptions are categorized into two main types: checked exceptions and
unchecked exceptions.

In Java, exceptions are categorized into two main types: checked exceptions and
unchecked exceptions. Additionally, there is a third category known as errors.
Let's delve into each of these types:

1. Checked Exception
2. Unchecked Exception
3. Error

Errors
Errors represent exceptional conditions that are not expected to be caught under
normal circumstances. They are typically caused by issues outside the control of
the application, such as system failures or resource exhaustion. Errors are not
meant to be caught or handled by application code. Examples of errors include:

OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot


allocate enough memory for the application.

StackOverflowError: It is thrown when the stack memory is exhausted due to


excessive recursion.

NoClassDefFoundError: It indicates that the JVM cannot find the definition of a


class that was available at compile-time.

Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This
means that the compiler verifies that the code handles these exceptions either
by catching them or declaring them in the method signature using the throws
keyword.

1. FileNotFoundException:
The FileNotFoundException is thrown while an attempt to get right of entry to a
record that does not exist or cannot be opened takes place. It is part of the java.io
package. example:

​ import java.io.File;
​ import java.io.FileNotFoundException;
​ import java.util.Scanner;
​ public class FileNotFoundExceptionExample {
​ public static void main(String[] args) {
​ try {
​ File = new File("nonexistent_file.txt");
​ Scanner = new Scanner(file);
​ } catch (FileNotFoundException e) {
​ System.out.println("File not found: " + e.getMessage());
​ }
​ }
​ }

2. IOException:
The IOException class is a well-known exception that suggests a mistake passed
off while acting enter/output operations. It is part of the java.io package. The
following program demonstrates the coping with of an IOException:

​ import java.io.BufferedReader;
​ import java.io.FileReader;
​ import java.io.IOException;

​ public class IOException {
​ public static void main(String[ ] args) {
​ String filePath = "example.txt";
​ try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
​ String line;
​ while ((line = reader.readLine()) != null) {
​ System.out.println(line);
​ }
​ } catch (IOException e) {
​ System.out.println("An error occurred while reading the
file:"+e.getMessage());
​ e.printStackTrace();
​ }
​ }
​ }

3. SQLException:
The SQLException is thrown when an error occurs while working with a database.
It is part of the java.sql package. The code snippet below illustrates a basic
scenario involving a database connection:

​ import java.sql.Connection;
​ import java.sql.DriverManager;
​ import java.sql.SQLException;
​ public class SQLExceptionExample {
​ public static void main(String[ ] args) {
​ try {

Connection=DriverManager.getConnection("jdbc:mysql://localhost:3306
/mydatabase","username", "password");
​ connection.close();
​ }
​ catch (SQLException e) {
​ System.out.println("SQL error occurred: " + e.getMessage());
​ }
​ }
​ }

4.ParseException:
The ParseException is thrown when an error occurs while parsing a string into a
selected format, along with a date or more than a few. It is part of the java.text
content package. Consider the following example:

ParseExceptionExample.java
​ import java.text.DateFormat;
​ import java.text.ParseException;
​ import java.text.SimpleDateFormat;
​ import java.util.Date;
​ public class ParseException {
​ public static void main(String[ ] args) {
​ DateFormat = new SimpleDateFormat("yyyy-MM-dd");
​ String invalidDate = "2023-13-45";
​ try {
​ Date parsedDate = dateFormat.parse(invalidDate);
​ System.out.println("Parsed date: " + parsedDate);
​ } catch (ParseException e) {
​ System.out.println("Invalid date format: " + e.getMessage());
​ }
​ }
​ }

5.nterruptedException:
The InterruptedException is thrown when a thread is interrupted while it is in a
sleeping or waiting state. It is often used to handle scenarios involving thread
synchronization and concurrency. Here's an example:

​ public class InterruptedExceptionExample {


​ public static void main(String[] args) {
​ try {
​ Thread.sleep(5000);
​ } catch (InterruptedException e) {
​ System.out.println("Thread interrupted: " + e.getMessage());
​ }
​ }
​ }

6.MalformedURLException:
The MalformedURLException is thrown when an invalid or malformed URL is
encountered. It is part of the java.net package. Consider the following program:

​ import java.net.MalformedURLException;
​ import java.net.URL;
​ public class MalformedURLException {
​ public static void main(String[] args) {
​ String invalidURL = "http://example.com";
​ try {
​ URL url = new URL(invalidURL);
​ System.out.println("Valid URL: " + url.toString());
​ } catch (MalformedURLException e) {
​ System.out.println("Malformed URL: " + e.getMessage());
​ }
​ }
​ }

7.ClassNotFoundException:
The ClassNotFoundException is thrown when an attempt is made to load a class
dynamically using the Class.forName() method, but the specified class cannot be
found.

​ public class ClassNotFoundException {


​ public static void main(String[] args) {
​ try {
​ Class = Class.forName("com.example.NonExistentClass");
​ } catch (ClassNotFoundException e) {
​ System.out.println("Class not found: " + e.getMessage());
​ }
​ }
​ }

Unchecked Exceptions (Runtime Exceptions)


Unchecked exceptions, also known as runtime exceptions, are not checked at
compile-time. These exceptions usually occur due to programming errors, such
as logic errors or incorrect assumptions in the code. They do not need to be
declared in the method signature using the throws keyword, making it optional
to handle them.

Types
Arithmetic exception : It is a type of unchecked error in code that is thrown
whenever there is a wrong mathematical or arithmetic calculation in the code,
especially during run time. For instance, when the denominator in a fraction is
zero, the arithmetic exception is thrown.
public class Arithmetic {

void divideInt(int n1, int n2) {

int res = n1 / n2;

System.out.println("Output: " + res);

public static void main(String argvs[]) {

ArithmeticException ae = new ArithmeticException();

ae.divideInt(1, 0);

NullPointerException : It is a runtime exception. It is thrown when a null


value is assigned to a reference object and the program tries to use that null
object
public class Tester {

public static void main(String[] args) {

Object ref = null;

ref.toString();

ArrayIndexOutOfBoundsException : It occurs when we access an array


with an invalid index. This means that either the index value is less than zero or
greater than that of the array’s length.
public class EgAOOB {

public static void main(String[] args) {

String[] arr = { "A", "B", "C", "D" };


for (int i = 0; i <= arr.length; i++) {

System.out.println(arr[i]);

NumberFormatException : It is a type of unchecked exception that occurs


when we are trying to convert a string to an int or other numeric value. This
exception is thrown in cases when it is not possible to convert a string to other
numeric types.
public class Example {

public static void main(String[] args) {

int a = Integer.parseInt(null);

InputMismatchException : It occurs when an input provided by the user is


incorrect. The type of incorrect input can be out of range or incorrect data type.
import java.util.Scanner;

public class InputEg {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter name: ");

String name = sc.next();

System.out.println("Enter age: ");

int age = sc.nextInt();

System.out.println(name);
System.out.println(age);

IllegalStateException : It is a runtime exception that occurs when a


method of a code is triggered or invoked at the wrong time. This exception is
used to give a signal that the method is invoked at the wrong time.
import java.util.ArrayList;
import java.util.ListIterator;

public class Example {

public static void main(String args[]) {


ArrayList<String> list = new ArrayList<String>();

list.add("apples");
list.add("mangoes");

ListIterator<String> it = list.listIterator();

it.remove();
}
}

You might also like