Exception
✔
An exception is an error or 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
Steps
for Exception Handling
- Find
the problem (Hit the problem)
- Inform
that an error has occurred (Throw the Exception)
- Receive
the error information (catch the exception)
- Take
corrective actions (Handle the exception)
Syntax
try
{
statement
that causes an error
}
catch(Exception_type e)
{
statement
to handle the error
}
Common
Java Exceptions
- ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation. - ArrayIndexOutOfBoundsException
It 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. - IOException
It is thrown when an input-output operation failed or interrupted - NumberFormatException
This exception is raised when a method could not convert a string into a numeric format. - FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
Example 01:
class exceptiondemo
{
public static void main(String arg[])
{
int
a=10;
int
b=5;
int
c=5;
int
x;
try
{
x=a/(b-c);
}
catch(ArithmeticException
e)
{
System.out.println(“Division
by zero error”);
}
}
}
Output:
Division by zero error
Example 02:
package Execption_Handling;
public class ArrayIndexOutOfBoundsExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5}; // Array of size 5
// Trying to access an invalid index
try {
System.out.println("Element at index 2: " + arr[2]); // Valid index
System.out.println("Element at index 5: " + arr[5]); // Invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
// Additional Example: Negative index
try {
System.out.println("Element at index -1: " + arr[-1]); // Invalid negative index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
}
}
Example 03:
package Execption_Handling;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class IOExceptionExample {
public static void main(String[] args) {
BufferedReader reader = null;
try {
// Trying to read from a file that may or may not exist
reader = new BufferedReader(new FileReader("testfile.txt"));
String line;
// Reading the file line by line
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Catch block to handle the IOException
System.out.println("An I/O error occurred: " + e.getMessage());
} finally {
try {
// Ensuring the reader is closed to release resources
if (reader != null) {
reader.close();
}
} catch (IOException e) {
// Exception handling if closing the reader fails
System.out.println("Failed to close the reader: " + e.getMessage());
}
}
}
}
Example 04:
package Execption_Handling;
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String validNumber = "123";
String invalidNumber = "123abc";
String emptyString = "";
String nullString = null;
try {
// Parsing a valid number
int num = Integer.parseInt(validNumber);
System.out.println("Parsed number: " + num);
// Trying to parse an invalid number
num = Integer.parseInt(invalidNumber);
System.out.println("Parsed number: " + num); // This will throw NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + e.getMessage());
}
try {
// Trying to parse an empty string
int num = Integer.parseInt(emptyString);
System.out.println("Parsed number: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number format (empty string): " + e.getMessage());
}
try {
// Trying to parse a null string
int num = Integer.parseInt(nullString);
System.out.println("Parsed number: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number format (null string): " + e.getMessage());
}
}
}
0 Comments