Exception Handling Collection Framework
Exception Handling Collection Framework
Framework
What is Exception
➔ In Java, Exception is an unwanted or unexpected event, which occurs
during the execution of a program, i.e. at run time, that disrupts the
normal flow of the program’s instructions.
➔ 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.
Major reasons why an exception
occurs:
➔ Invalid user input
➔ Device failure
➔ Loss of network connection
➔ Physical limitations (out-of-disk memory)
➔ Code errors
➔ Opening an unavailable file
Difference between Error and
Exception
● Error: An Error indicates a serious problem that a reasonable
application should not try to catch.
● Exception: Exception indicates conditions that a reasonable application
might try to catch.
Error Example: Out of Memory Error
import java.util.ArrayList;
import java.util.List;
class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{ Output
System.out.println(a/b); java.lang.ArithmeticExcept
} ion: / by zero
catch(ArithmeticException e){ at GFG.main(File.java:10)
e.printStackTrace();
}
}
}
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: Exception handling using
try...catch
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"); Output:
} ArithmeticException => / by zero
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
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.
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
Example: Java Exception Handling using
finally block
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
} Output:
finally {
System.out.println("This is the finally block");
}
}
}
What Are Custom Exceptions?
● Custom exceptions allow developers to define their own exception types for
specific application needs.
● Useful for handling application-specific errors more effectively.
● Created by extending the Exception or RuntimeException class.
class Main {
public static void validateAge(int age) throws CustomException
{
if (age < 18) {
throw new CustomException("Age must be 18 or older.");
}
}