Built-in and custom exceptions

 

Java provides a rich Exception Handling mechanism that allows us to:

  • Use built-in exceptions for common error conditions.

  • Create our own custom exceptions to represent application-specific problems.


🔹 1. Built-in Exceptions

🔸 What are they?

These are predefined exception classes in the Java standard library (in java.lang and other packages).

🔸 Types:

CategoryExamples
Unchecked Exceptions (subclass of RuntimeException)ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
Checked Exceptions (subclass of Exception but not RuntimeException)IOException, SQLException, ClassNotFoundException

📘 Example: Using a Built-in Exception

public class BuiltInExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[5]); // out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught: " + e);
}
}
}

🔹 2. Custom Exceptions

🔸 What are they?

Custom (user-defined) exceptions are classes you create by extending the Exception class (or its subclasses) to represent specific error conditions in your application.

✅ Why use custom exceptions?

  • To provide meaningful names to exceptions.

  • To handle business logic errors more cleanly.

  • To keep the code more readable and modular.


🔧 How to Create a Custom Exception

Step 1: Create a class that extends Exception or RuntimeException

class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}

Step 2: Use throw and throws to use it


public class CustomExceptionDemo {
public static void main(String[] args) {
try {
checkAge(15);
} catch (MyCustomException e) {
System.out.println("Custom Exception Caught: " + e.getMessage());
}
}
static void checkAge(int age) throws MyCustomException {
if (age < 18) {
throw new MyCustomException("Age must be 18 or above.");
}
System.out.println("Access granted.");
}
}

🔁 Comparison Table

FeatureBuilt-in ExceptionsCustom Exceptions
Defined byJava API (java.lang, java.io, etc.)Programmer/User-defined
PurposeHandle general errors like null, IO, etc.Handle application-specific errors
Need to write new class?❌ No✅ Yes
ExamplesNullPointerException, IOExceptionInsufficientFundsException, InvalidInputException
Extend fromException or RuntimeExceptionSame

🧠 Best Practice

  • Use built-in exceptions for general coding errors.

  • Use custom exceptions to clearly indicate and handle business rule violations or application-specific issues.

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism