Interface in Java:
⭐ What is an Interface in Java?
An interface in Java is like a blueprint of a class.
It contains only method declarations (without body) and constants.
✔ It tells what a class must do
❌ but not how it will do it
All methods in an interface are:
public
abstract (before Java 8)
no method body
Example:
interface Animal {
void sound(); // abstract method
void eat(); // abstract method
⭐ Why do we use Interfaces?
Interfaces are used for:
1. Achieving 100% abstraction
2. Multiple inheritance (Java classes cannot do this directly)
3. Standardization → Everyone must follow same rules
4. Loose coupling → Easy to change or update
⭐ Characteristics of Interfaces
You cannot create objects of an interface
(new InterfaceName() is not allowed)
A class that uses an interface must implement it using the keyword implements
A class must give body to ALL interface methods
A class can implement multiple interfaces
⭐ Basic Example of Interface
Step 1: Define interface
interface Animal {
void sound();
void eat();
Step 2: Implement interface
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
public void eat() {
[Link]("Dog eats bones");
Step 3: Use in main
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
⭐ Output
Dog barks
Dog eats bones
⭐ Why do we need interface? (Simple example)
Imagine a rule:
Every vehicle MUST have brake.
So we create an interface:
interface Brake {
void applyBrake();
Now all vehicles must follow the rule:
class Car implements Brake {
public void applyBrake() {
[Link]("Car brake applied");
class Bike implements Brake {
public void applyBrake() {
[Link]("Bike brake applied");
class Truck implements Brake {
public void applyBrake() {
[Link]("Truck brake applied");
Even though Vehicle types are different, they follow same rule.
⭐ Multiple Inheritance Using Interface
Java does not allow:
class A extends B, C // ❌ not allowed
But it allows this:
class A implements X, Y // ✔ allowed
Example:
interface X {
void methodX();
interface Y {
void methodY();
class Demo implements X, Y {
public void methodX() {
[Link]("X method");
public void methodY() {
[Link]("Y method");
⭐ Interface with Variables
Variables in interfaces are:
public
static
final
Automatically!
Example:
interface MyInterface {
int a = 10; // final constant
Trying to change value is not allowed:
MyInterface.a = 20; // ❌ ERROR
⭐ From Java 8 Onwards
Interfaces can also have:
✔ Default methods (has body)
default void message() {
[Link]("Hello from default method");
✔ Static methods
static void info() {
[Link]("Static method in interface");
⭐ Full Example (Modern Interface)
interface A {
void show(); // abstract method
default void msg() { // default method
[Link]("Default method in interface");
static void display() { // static method
[Link]("Static method in interface");
class B implements A {
public void show() {
[Link]("Show method implemented in class B");
public class Test {
public static void main(String[] args) {
B obj = new B();
[Link]();
[Link]();
[Link]();
⭐ Output
Show method implemented in class B
Default method in interface
Static method in interface
⭐ When to Use Interfaces? (Very important for viva)
Use an interface when:
Many classes must follow the same rules
You want 100% abstraction
You want to achieve multiple inheritance
You want to make code flexible and maintainable
⭐ Quick Viva Questions (With Answers)
1. What is interface?
→ A blueprint of class that contains abstract methods.
2. Can interface have constructor?
→ No.
3. Are all methods public and abstract?
→ Yes, by default.
4. Can we create object of interface?
→ No.
5. Can a class implement multiple interfaces?
→ Yes.
6. Variables inside interface are?
→ public, static, final.
What is ENUM:
⭐ What is an Enum in Java?
An Enum (short for enumeration) in Java is a special type used to define a group of constant values.
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
Enums help represent things that never change.
⭐ Why do we use Enum?
Because enums:
✔ Make code more readable
✔ Prevent invalid values
✔ Replace hard-coded strings or integers
✔ Represent fixed sets (like days, directions, colors)
Example:
Instead of:
int RED = 1;
int GREEN = 2;
int BLUE = 3;
We use:
enum Color { RED, GREEN, BLUE }
Cleaner and safer!
⭐ Basic Enum Example
enum Color {
RED, GREEN, BLUE
public class Test {
public static void main(String[] args) {
Color c = [Link];
[Link](c);
Output:
RED
⭐ Enum is a Class (Internally)
Enums look simple, but internally they behave like classes.
Each constant is like a public static final object.
For example:
[Link]
is a constant object of type Color.
⭐ Enum with Switch Case
Enums work beautifully with switch:
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Test {
public static void main(String[] args) {
Day d = [Link];
switch (d) {
case MONDAY: [Link]("Start of week"); break;
case TUESDAY: [Link]("Second day"); break;
case WEDNESDAY: [Link]("Midweek"); break;
}
⭐ Enum with Fields, Constructor, Methods
Enums can have:
✔ variables
✔ constructors
✔ methods
Example:
enum Mobile {
APPLE(150000),
SAMSUNG(90000),
ONEPLUS(50000);
int price;
Mobile(int price) {
[Link] = price;
int getPrice() {
return price;
public class Test {
public static void main(String[] args) {
[Link]([Link]());
Output:
150000
⭐ Important Features of Enum
1. Enum constants are public static final
2. Enum cannot be extended (they implicitly extend [Link])
3. Enum can implement interfaces, but cannot extend classes
4. Enum constructors are always private
5. Enums are type-safe (only valid values allowed)
⭐ Real-Life Uses of Enums
Months (JAN, FEB…)
Days (MONDAY…)
Directions (NORTH, SOUTH…)
Status (SUCCESS, FAILED, RUNNING)
Mobile brands
Traffic signals (RED, YELLOW, GREEN)
Example:
enum Signal {
RED, YELLOW, GREEN
⭐ Quick Viva Questions (with Answers)
1. What is Enum?
A special data type used to store a group of constant values.
2. Can Enum have methods?
Yes.
3. Can Enum extend a class?
No (already extends [Link]).
4. Can Enum implement interfaces?
Yes.
5. Is Enum type-safe?
Yes, only valid enum values are allowed.
6. What is the default base class of Enum?
[Link].
What is Annotation:
✅ What is an Annotation in Java?
An annotation is a special symbol/marker in Java that you attach to classes, methods, variables, etc.,
to give additional information to the compiler, tools, or the Java program itself.
It does NOT change how your code runs directly.
It just provides metadata (information about your code).
Example:
@Override
public void run() { }
Here, @Override is an annotation.
✔ Why do we use Annotations?
Annotations help to:
1. Give instructions to the compiler
Example:
@Override tells the compiler:
“this method must override a method from the parent class.”
2. Automatically generate code
Tools like Lombok, frameworks like Spring use annotations to generate code.
3. Provide information to frameworks
Spring Boot, Hibernate, JUnit depend heavily on annotations.
Example:
@Autowired
4. Control how a program behaves at runtime
Annotations can be read using Reflection.
✔ Where can you use annotations?
You can apply annotations on:
class
method
variable
parameter
constructor
package
Example:
@SuppressWarnings("unchecked")
public class Test {
✔ Most Common Java Annotations
1. @Override
Checks if a method is overriding correctly.
@Override
public void toString() { }
2. @Deprecated
Marks a method/class as outdated.
@Deprecated
public void oldMethod() { }
3. @SuppressWarnings
Hides compiler warnings.
@SuppressWarnings("unchecked")
4. @FunctionalInterface
Ensures the interface has exactly one abstract method.
@FunctionalInterface
interface MyFunc {
void test();
5. @Retention & @Target
Used when creating custom annotations.
🔥 Custom Annotation Example (Very Important)
You can create your own annotation like this:
import [Link].*;
@Retention([Link])
@Target([Link])
public @interface MyAnnotation {
String value();
Use it like this:
@MyAnnotation(value = "Hello")
public void display() { }
✔ How to Read Annotation at Runtime?
Using Reflection:
Method m = [Link]().getMethod("display");
MyAnnotation an = [Link]([Link]);
[Link]([Link]());
🧠 Why are annotations important?
Because modern Java frameworks massively depend on them:
Spring
@RestController
@Autowired
@RequestMapping
JUnit
@Test
@BeforeEach
Hibernate
@Entity
@Table
@Column
They reduce code, improve readability, and control framework behavior.
🎯 Simple Definition (easy to remember)
Annotation = A tag that gives information to compiler, tools, or JVM.
It does not change the execution directly but influences how code is treated.
✅ What is a Functional Interface?
A Functional Interface is an interface that has exactly ONE abstract method.
👉 You can write many default or static methods,
but only one abstract method is allowed.
📌 Examples:
Runnable → run()
Callable → call()
Comparable → compareTo()
Comparator → compare()
✔ Why do we use Functional Interfaces?
Functional Interfaces allow:
Lambda Expressions
Method References
Cleaner, shorter code
Example with Lambda:
@FunctionalInterface
interface Calculator {
int add(int a, int b);
Calculator c = (x, y) -> x + y;
[Link]([Link](5, 3));
✔ @FunctionalInterface Annotation
This annotation ensures the interface has only ONE abstract method.
@FunctionalInterface
interface MyInterface {
void show();
If you add another abstract method → error.
🎯 Key Point
👉 If an interface has one abstract method → automatically considered Functional Interface.
Annotation is optional, but recommended.
--------------------------
⭐ Types of Interfaces in Java
There are 5 types of interfaces in Java.
1️⃣ Normal Interface
Contains any number of abstract methods.
interface A {
void m1();
void m2();
2️⃣ Functional / Single Abstract Method (SAM) Interface
Contains only one abstract method.
@FunctionalInterface
interface B {
void show();
}
Used in Lambda Expressions.
3️⃣ Marker Interface
Contains zero methods.
Used for marking/identification.
Examples:
Serializable
Cloneable
Remote
interface MyMarker { }
These interfaces do not contain methods but give special meaning to classes.
4️⃣ SAM Interface (same as Functional Interface)
SAM → Single Abstract Method
Same as Functional Interface.
Example: Runnable, Comparable.
5️⃣ Tag Interface (same as Marker Interface)
Tag = Marker
Both mean zero-method interfaces.
6️⃣ Hybrid Interfaces (multiple inheritance)
Interface that extends multiple interfaces.
interface A { void m1(); }
interface B { void m2(); }
interface C extends A, B { }
7️⃣ Default Method Interface (Java 8+)
Interfaces that contain default methods.
interface Test {
default void show() {
[Link]("Default method");
You can add:
default methods
static methods
--------------------------
🔥 Summary Table (Easy for Exams)
Type of Interface Abstract Methods Example
Normal 1 or more List, Map
Functional/SAM Exactly 1 Runnable, Comparable
Marker/Tag 0 Serializable, Cloneable
Hybrid Multiple inheritance C extends A, B
Default Method Interface (Java 8+) Any number + default/static Custom
🎯 2-Line Exam Definition
Functional Interface
“An interface that contains exactly one abstract method is called a Functional Interface. It is used to
implement lambda expressions.”
Types of Interfaces
“Interfaces are classified into Normal Interface, Functional Interface, Marker Interface, Hybrid
Interface, and Default Method Interface.”
✅ What is a Lambda Expression?
A lambda expression is a short way of writing a method (usually from a functional interface).
It is mainly used in functional programming and streams.
A lambda expression:
(parameters) -> { body }
✅ Functional Interface
A lambda expression can be used only with functional interfaces, i.e., interfaces with exactly one
abstract method.
Example:
@FunctionalInterface
interface Addition {
int add(int a, int b);
⭐ Lambda Expression WITH RETURN VALUE
When the method returns a value, the lambda expression should also return a value.
Example 1: Lambda with return
Addition add = (a, b) -> {
return a + b;
};
Short version (no need of return keyword):
Addition add = (a, b) -> a + b;
Full program
@FunctionalInterface
interface Addition {
int add(int a, int b);
public class LambdaDemo {
public static void main(String[] args) {
Addition obj = (a, b) -> a + b; // lambda expression with return
[Link]("Result: " + [Link](10, 20));
⭐ Output
Result: 30
🟦 Lambda Expression WITHOUT return (void method)
If your method does NOT return anything:
Functional interface:
@FunctionalInterface
interface Addition {
void add(int a, int b);
Lambda:
Addition obj = (a, b) -> {
[Link](a + b);
};
⚠ Important Notes
❌ A lambda expression does NOT use method name.
❌ It cannot be written directly inside an interface.
Your earlier code:
public interface Addtion {
(int a,int b)-> { [Link](a+b); }
This is wrong, because:
Lambda cannot be written inside interface
Interface should contain only method declaration
The correct way:
@FunctionalInterface
interface Addition {
void add(int a, int b);
class Test {
public static void main(String[] args) {
Addition a = (x, y) -> [Link](x + y);
[Link](10, 20);
⭐ What is an Exception?
An exception is an unexpected event or error that occurs during program execution and stops the
normal flow of the program.
🔹 Examples of Exceptions:
Dividing a number by zero → ArithmeticException
Accessing array index out of range → ArrayIndexOutOfBoundsException
Number format error → NumberFormatException
File not found → FileNotFoundException
Null reference used → NullPointerException
✔ In simple words:
Exception = Runtime error.
⭐ What is Exception Handling?
Exception Handling is a mechanism to detect, handle, and continue program execution even when
an error occurs.
Java provides five keywords:
1. try
2. catch
3. finally
4. throw
5. throws
⭐ Exception Handling using try–catch
🔹 Syntax
try {
// code that may cause an exception
catch (Exception e) {
// handling code
✔ What happens?
Code in try block is executed.
If an exception occurs, program jumps to catch block.
Program continues normally after catch block.
⭐ Example Program (Easy & Perfect for Viva)
Example 1: Division by zero
public class Example {
public static void main(String[] args) {
try {
int a = 10 / 0; // risky code
catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
[Link]("Program continues...");
✔ Output:
Cannot divide by zero!
Program continues...
⭐ Example 2: Array Index Exception
try {
int arr[] = {10, 20, 30};
[Link](arr[5]); // wrong index
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Invalid array index!");
⭐ Why do we need Exception Handling?
✔ Prevents program from sudden termination
✔ Helps fix or avoid runtime errors
✔ Increases reliability
✔ Allows showing proper error messages
⭐ Keywords Used in Exception
Handling in Java
Java provides 5 main keywords for exception handling:
1️⃣ try
2️⃣ catch
3️⃣ finally
4️⃣ throw
5️⃣ throws
Let’s understand each one clearly with examples.
⭐ 1. try
🔹 Meaning:
The try block contains risky code that may produce an exception.
🔹 Syntax:
try {
// risky code
🔹 Example:
try {
int a = 10 / 0;
⭐ 2. catch
🔹 Meaning:
The catch block handles the exception that occurs in the try block.
🔹 Syntax:
catch (ExceptionType e) {
// handling code
🔹 Example:
catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
⭐ 3. finally
🔹 Meaning:
finally block always executes, whether an exception occurs or not.
Used for closing resources: files, database, network connection, etc.
🔹 Syntax:
finally {
// cleanup code (always runs)
🔹 Example:
try {
int a = 10 / 0;
}
catch (Exception e) {
[Link]("Error");
finally {
[Link]("This always executes!");
✔ Output:
Error
This always executes!
⭐ 4. throw
🔹 Meaning:
throw is used to manually throw an exception.
You create an exception object and throw it.
🔹 Syntax:
throw new ExceptionType("message");
🔹 Example:
if (age < 18) {
throw new ArithmeticException("Not eligible");
⭐ 5. throws
🔹 Meaning:
throws is used in method declaration to declare that a method might throw an exception.
Used when you want to pass the exception to the caller instead of handling it.
🔹 Syntax:
void myMethod() throws ExceptionType {
// code
🔹 Example:
public void readFile() throws FileNotFoundException {
FileInputStream f = new FileInputStream("[Link]");
This means:
➡ The method may throw FileNotFoundException
➡ Whoever calls this method must handle it
⭐ Summary Table (Easy to Remember)
Keyword Purpose Executes When?
try Holds risky code Always
catch Handles exception Only when an exception occurs
Always (even if exception or return statement
finally Cleanup code
occurs)
throw Manually throw exception When programmer wants
Declares exceptions in method
throws At compile time
signature
⭐ Short Program Using All Keywords
public class Test {
public static void main(String[] args) {
try {
checkAge(15);
catch (Exception e) {
[Link]([Link]());
finally {
[Link]("Program ended.");
static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Age must be 18 or above");
⭐ 1. throw Keyword (Manual
Exception Throwing)
✔ Meaning:
throw is used to manually create and throw an exception.
You use it inside a method.
✅ Example of throw
Program: Throwing exception for negative age
public class ThrowExample {
public static void main(String[] args) {
int age = -5;
if (age < 0) {
throw new ArithmeticException("Age cannot be negative");
[Link]("Valid age: " + age);
✔ Output:
Exception in thread "main" [Link]: Age cannot be negative
✔ Explanation:
We manually throw an exception using throw new ArithmeticException(...)
Program stops immediately when exception is thrown.
⭐ When to use throw?
✔ To validate user input
✔ To stop execution when conditions are wrong
✔ To raise custom errors
⭐ 2. throws Keyword (Declaring Exception
in Method Signature)
✔ Meaning:
throws is used to declare that a method may cause an exception,
but the method does NOT handle it.
The exception is passed to the caller.
✅ Example of throws
Program: Declaring FileNotFoundException
import [Link].*;
public class ThrowsExample {
public static void main(String[] args) throws IOException {
readFile();
static void readFile() throws IOException {
FileInputStream f = new FileInputStream("[Link]");
[Link]("File opened successfully");
}
✔ Explanation:
readFile() may cause IOException
Instead of handling it inside the method, we say:
throws IOException
Now the exception is the responsibility of the caller (main() method).
⭐ Easy Difference to Remember
throw throws
Used inside method Used in method declaration
Manually throws exception Declares that method may throw exception
Throws one exception at a time Can declare multiple exceptions
Runtime action Compile-time declaration
⭐ Combined Example (throw + throws)
class Test {
static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Not eligible, age must be 18+");
[Link]("Eligible");
public static void main(String[] args) {
try {
checkAge(16);
catch (Exception e) {
[Link]([Link]());
}
}
✔ Output:
Not eligible, age must be 18+
Exception Hierarchy —
explained clearly and in detail
Think of Java’s exception system as a family tree. At the root is Throwable. Everything that can be
"thrown" or "caught" comes from this root. I’ll walk you down the tree, explain each branch, show
examples, and cover important behaviors and best practices.
The tree (top-level)
[Link]
├── [Link]
└── [Link]
├── [Link] (unchecked)
└── (checked exceptions like IOException, SQLException, etc.)
Throwable
Root of the hierarchy.
Provides basic methods:
o getMessage() — short message.
o printStackTrace() — full stack trace.
o getCause() — chained cause.
You rarely extend Throwable directly — prefer extending Exception or RuntimeException.
Error (major branch)
Subclasses represent serious problems that applications usually should not try to catch.
Examples:
o OutOfMemoryError
o StackOverflowError
o VirtualMachineError
These indicate problems in the JVM or environment, not normal program logic.
Do not handle unless you have a very special reason.
Exception (major branch)
This is for conditions your program might want to catch or declare.
Split into two important groups:
1. Checked Exceptions
Subclasses of Exception except RuntimeException and its subclasses.
Examples: IOException, SQLException, ClassNotFoundException, FileNotFoundException.
Compile-time rule: You must either handle them with try-catch or declare them with throws
in the method signature.
Use when the caller can reasonably recover (e.g., file missing → ask user / try different file).
Example (checked):
void read() throws IOException {
FileInputStream in = new FileInputStream("[Link]"); // may throw FileNotFoundException
2. Unchecked Exceptions (RuntimeExceptions)
Subclasses of RuntimeException.
Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException,
IllegalArgumentException.
No compile-time requirement to declare or catch.
Usually indicate programmer errors (bad API usage, logic bugs).
Prefer fixing the cause rather than catching them broadly.
Example (unchecked):
int divide(int a, int b) {
return a / b; // may throw ArithmeticException at runtime if b == 0
}
Common and useful exceptions (quick reference)
Type Common classes Meaning
External issues (IO, DB, class
Checked IOException, SQLException, ClassNotFoundException
loading)
NullPointerException, IndexOutOfBoundsException, Programmer errors /
Unchecked
IllegalArgumentException incorrect usage
Error OutOfMemoryError, StackOverflowError JVM or environment failure
Exception propagation & stack traces
When an exception is thrown and not caught in the current method, it propagates up the call
stack to the caller.
If it reaches main without being caught, the JVM prints the stack trace and terminates the
thread.
Stack trace shows exception type, message, and the call stack (helps debug where it
happened).
[Link]: Cannot read property ...
at [Link]([Link])
at [Link]([Link])
Catching order & best practice
Catch specific exceptions first, then more general ones.
Compiler enforces no unreachable catch blocks (you can’t catch Exception first then
IOException).
Prefer not to catch Exception or Throwable unless you have a clear reason (logging at top
level, cleanup, shutdown hooks).
try {
// risky code
} catch (FileNotFoundException e) {
// handle file missing
} catch (IOException e) {
// handle other IO problems
} catch (Exception e) {
// fallback (rare)
}
Multi-catch (Java 7+)
Catch multiple exceptions in a single catch using |.
The caught exception variable is effectively final (you cannot assign to it).
try {
// ...
} catch (IOException | SQLException ex) {
[Link]();
finally and try-with-resources
finally runs always (except when JVM exits abruptly), useful to release resources.
try-with-resources (Java 7+) automatically closes AutoCloseable resources and is preferred.
try (FileInputStream in = new FileInputStream("[Link]")) {
// use input
} catch (IOException e) {
// handle
} // [Link]() auto-called
Creating custom exceptions
Extend Exception for a checked custom exception.
Extend RuntimeException for an unchecked custom exception.
// Checked
public class MyCheckedException extends Exception {
public MyCheckedException(String msg) { super(msg); }
// Unchecked
public class MyRuntimeException extends RuntimeException {
public MyRuntimeException(String msg) { super(msg); }
}
Use checked when caller must handle the problem; use unchecked for programming errors or when
forcing caller to handle is unwieldy.
Exception chaining (cause)
You can pass a cause when throwing a new exception to preserve original exception:
try {
// code that throws SQLException
} catch (SQLException e) {
throw new MyCheckedException("DB failed", e); // chain cause
Use Throwable#getCause() to inspect the original cause.
Suppressed exceptions
In try-with-resources, if an exception is thrown in try and another occurs during resource
closing, the latter is suppressed and attached to the primary exception. Use getSuppressed()
to inspect them.
Practical guidelines / best practices
1. Prefer specific exceptions in catch blocks — handle known problems clearly.
2. Don’t use exceptions for flow control. They’re for exceptional situations.
3. Document checked exceptions with throws and JavaDoc so callers know what to expect.
4. Avoid swallowing exceptions silently (catch(Exception e) {} should at least log).
5. Use try-with-resources to manage resources.
6. Use RuntimeException for programming errors; use checked exceptions for recoverable
conditions.
7. Add context when rethrowing (exception chaining) so debugging is easier.
Examples — short snippets
Example 1: Checked exception propagation
void read() throws IOException {
[Link]([Link]("[Link]")); // may throw IOException
}
public static void main(String[] args) {
try {
read();
} catch (IOException e) {
[Link]("File missing or read error: " + [Link]());
Example 2: Custom unchecked exception
public class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String msg) { super(msg); }
void setAge(int age) {
if (age < 0) throw new InvalidAgeException("Age < 0");
Quick recap (one-liner)
Throwable → Error (don’t catch) and Exception (catchable).
Exception → checked (must declare/handle) and unchecked (RuntimeException, programmer
errors).
Use try/catch/finally, prefer try-with-resources, create custom exceptions when needed, and
always preserve original causes when rethrowing.
⭐ What is a Custom
Exception?
A Custom Exception (User-defined Exception) is an exception created by the programmer to handle
application-specific errors that Java’s built-in exceptions cannot describe.
✔ Why do we need Custom Exceptions?
Sometimes built-in exceptions like
NullPointerException, ArithmeticException, IOException
do NOT match a specific business rule.
Example:
Age must not be negative
Username should not contain spaces
Salary cannot be zero
Student marks must be between 0–100
In such cases, we create our own exception class.
⭐ How to Create a Custom Exception?
A custom exception is created by extending either:
✔ Exception → Checked Custom Exception
or
✔ RuntimeException → Unchecked Custom Exception
⭐ 1. Checked Custom Exception Example
👉 Checked exceptions must be handled (try-catch or throws).
Step 1: Create Custom Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
Step 2: Use the Custom Exception
public class Test {
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above");
[Link]("Eligible!");
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (InvalidAgeException e) {
[Link]([Link]());
✔ Output:
Age must be 18 or above
⭐ 2. Unchecked Custom Exception Example (RuntimeException)
👉 Unchecked exceptions do not need try–catch.
(Programmer error or invalid logic)
Step 1: Create Custom Exception
class NegativeNumberException extends RuntimeException {
public NegativeNumberException(String message) {
super(message);
Step 2: Use it
public class Test2 {
static void check(int n) {
if (n < 0) {
throw new NegativeNumberException("Number cannot be negative");
[Link]("Valid number!");
}
public static void main(String[] args) {
check(-10);
✔ Output:
Exception in thread "main" NegativeNumberException: Number cannot be negative
⭐ Difference: Checked vs Unchecked Custom Exception
Type Extend Must handle? Use for
Checked Custom Yes (try–catch / Recoverable conditions (file missing,
Exception
Exception throws) invalid age, etc.)
Unchecked Custom Programming errors (invalid number,
RuntimeException No
Exception wrong format, etc.)
⭐ When should you create custom exceptions?
Use Custom Exceptions when:
✔ You want a meaningful message
✔ You want business rule validation
✔ You want to clearly identify the error type
✔ Java built-in exceptions do not match your logic