0% found this document useful (0 votes)
11 views25 pages

Java Unit3 Notes

This document provides comprehensive notes on Java programming, focusing on packages, interfaces, and exception handling. It covers definitions, implementations, access protection, importing packages, and exception hierarchy, including checked and unchecked exceptions. The notes are structured for exam preparation, detailing key concepts and examples for each topic.

Uploaded by

Avdhesh Dadhich
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)
11 views25 pages

Java Unit3 Notes

This document provides comprehensive notes on Java programming, focusing on packages, interfaces, and exception handling. It covers definitions, implementations, access protection, importing packages, and exception hierarchy, including checked and unchecked exceptions. The notes are structured for exam preparation, detailing key concepts and examples for each topic.

Uploaded by

Avdhesh Dadhich
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

JAVA PROGRAMMING

Packages · Interfaces · Exception Handling

Complete Exam-Oriented Notes | Unit III

TABLE OF CONTENTS
# Topic Key Concepts

1 Packages – Definition & Implementationpackage declaration, import, classpath, sub-packages

2 Access Protection in Packages public/protected/private visibility across packages

3 Importing Packages import statement, wildcard, static import, [Link]

4 Interfaces – Definition & Implementationinterface, implements, default/static methods, multiple

5 Exception Handling – Fundamentals Throwable hierarchy, checked vs unchecked, Error vs Exception

6 try and catch try block, catch block, exception object, getMessage()

7 Multiple catch Clauses multi-catch, catch ordering, most-specific first rule

8 Nested try Statements try inside try, propagation, inner/outer catch

9 throw and finally manual throw, finally guarantee, throw vs throws

10 User-Defined Exceptions custom exception class, extending Exception/RuntimeException

Java Programming | Packages · Interfaces · Exception Handling Page 1


1 PACKAGES – DEFINITION & IMPLEMENTATION

DEFINITION
Formal: A package in Java is a namespace that organizes a set of related classes and interfaces. Packages
serve as a directory structure for Java bytecode files (.class files). They prevent naming conflicts, control access
to classes, and make it easier to locate and use classes, interfaces, enumerations, and annotations.

Conceptual: Think of packages like folders on your computer. Just as you put related documents in one folder,
Java lets you group related classes into one package. Two files with the same name can live in different folders
— similarly, two classes with the same name can coexist in different packages.

Why it exists: In large programs with hundreds of classes, packages prevent name collisions, improve
organization, and provide an extra layer of access protection beyond just public/private.

1.1 Package Declaration


The package statement must be the very FIRST statement in a Java source file (before any imports or class
declarations). Only one package declaration is allowed per file. If omitted, the class belongs to the default
(unnamed) package.

// Package Declaration

// File: com/myapp/utils/[Link]

package [Link]; // MUST be first statement

public class MathHelper {

public static int square(int n) { return n * n; }

public static int cube(int n) { return n * n * n; }

1.2 Directory Structure


The package name directly maps to the directory (folder) structure on disk. The JVM uses this mapping to locate
.class files.

// Directory Structure

// Package: [Link]

// Disk: com/myapp/utils/[Link]

// Folder structure:

project/

com/

myapp/

utils/

[Link]

[Link]

Java Programming | Packages · Interfaces · Exception Handling Page 2


model/

[Link]

// Compile: javac com/myapp/utils/[Link]

// Run: java [Link]

1.3 Sub-packages
Packages can be nested using dots (.). [Link] is a sub-package of java. Sub-packages are INDEPENDENT —
importing [Link] does NOT import [Link] automatically. They are purely an organizational convention.

■ Memory Trick: Package name = Reverse domain name + project path. e.g., company domain [Link] →
package [Link]

■ EXAM Q: What is a package? How do you create and use a package in Java?

■ EXAM Q: Where must the package statement appear in a Java source file?

1.4 Built-in Java Packages


Package Contains Auto-imported?

[Link] String, Math, Object, System, Integer… ■ YES – always

[Link] ArrayList, HashMap, Scanner, Date… ■ Must import

[Link] File, InputStream, BufferedReader… ■ Must import

[Link] URL, Socket, HttpURLConnection… ■ Must import

[Link] Connection, Statement, ResultSet… ■ Must import

[Link] Button, Frame, Color (GUI)… ■ Must import

[Link] JFrame, JButton, JLabel (GUI)… ■ Must import

■ EXAM TRAP: [Link] is the ONLY automatically imported package. All others need an explicit import
statement.

Java Programming | Packages · Interfaces · Exception Handling Page 3


2 ACCESS PROTECTION IN PACKAGES

DEFINITION
Formal: Access protection (access control) in Java defines rules for which classes, subclasses, and code
outside a package can access class members (fields, methods, constructors). Java provides four access
modifiers — public, protected, default (package-private), and private — each with different levels of visibility that
become especially significant when packages are involved.

Why it matters for packages: Without packages, you only needed class-level access control. With packages,
you need to control visibility across package boundaries.

Modifier Same Class Same Package Subclass (diff pkg) Diff Package

private ■ ■ ■ ■

default ■ ■ ■ ■

protected ■ ■ ■ ■

public ■ ■ ■ ■

Key Rules for Protected across Packages


The protected modifier has a subtle rule: a subclass in a DIFFERENT package can only access a protected
member through an instance of the subclass itself (not through a parent class reference). This is the most
frequently misunderstood aspect of access control.

// Protected Access Across Packages

// Package: animals

package animals;

public class Animal {

protected String sound = "generic";

public void speak() { [Link](sound); }

// Package: pets (different package)

package pets;

import [Link];

public class Dog extends Animal {

public void test() {

sound = "Woof"; // ■ OK — accessed via 'this' (subclass instance)

Dog d = new Dog();

[Link] = "Bark"; // ■ OK — still subclass reference

// Animal a = new Animal(); [Link] = "x"; ← COMPILE ERROR

Java Programming | Packages · Interfaces · Exception Handling Page 4


}

■ EXAM Q: Explain the complete access protection table with cross-package examples.

■ EXAM Q: What is the difference between default and protected access?

Java Programming | Packages · Interfaces · Exception Handling Page 5


3 IMPORTING PACKAGES

DEFINITION
Formal: The import statement in Java allows a class to use classes and interfaces from other packages without
needing to use their fully qualified names. Import statements appear after the package declaration but before the
class declaration. They do NOT physically include code — they simply tell the compiler where to look.

Simple: Instead of writing [Link] every time, you write import [Link]; once at the top, and
then use just ArrayList throughout the file.

// Import Forms

// Form 1: Import a specific class

import [Link];

import [Link];

// Form 2: Wildcard import — imports ALL classes in [Link]

import [Link].*; // Does NOT import sub-packages!

// Form 3: Static import — import static members directly

import static [Link];

import static [Link];

// Form 4: Fully Qualified Name — no import needed

[Link] sc = new [Link]([Link]);

public class ImportDemo {

public static void main(String[] args) {

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

[Link]("Java"); [Link]("Python");

[Link]("PI = " + PI); // static import

[Link]("sqrt(16) = " + sqrt(16)); // static import

[Link](list);

OUTPUT:

PI = 3.141592653589793

sqrt(16) = 4.0

[Java, Python]

Import Type Syntax Note

Specific class import [Link]; Best practice — explicit

Java Programming | Packages · Interfaces · Exception Handling Page 6


Wildcard import [Link].*; Lazy but no performance penalty

Static import import static [Link].*; Avoids repetitive [Link] calls

Fully qualified [Link] d = new…; No import needed; verbose

Auto ([Link]) (nothing required) String, Math, Object auto-available

■ EXAM TRAP: Wildcard import ([Link].*) does NOT import sub-packages. [Link].* does NOT give you
[Link].

■ EXAM TRAP: import statements do NOT add code size or slow programs — they're just hints to the
compiler.

■ EXAM Q: Difference between import [Link] and import [Link].*

Java Programming | Packages · Interfaces · Exception Handling Page 7


4 INTERFACES – DEFINITION & IMPLEMENTATION

DEFINITION
Formal: An interface in Java is a reference type, similar to a class, that is a collection of abstract methods and
constants. A class implements an interface by providing implementations for all the abstract methods declared in
the interface. Interfaces define a contract — they specify WHAT a class must do without dictating HOW it does it.

Conceptual: Think of an interface as an agreement/contract. If your class signs the contract (implements the
interface), it MUST fulfill all the obligations (implement all the methods). For example, a Printable interface says
'anything Printable must have a print() method' — but how each class prints is its own business.

Why it exists: Java does not support multiple class inheritance (a class cannot extend two classes). But a class
CAN implement multiple interfaces. Interfaces provide a workaround for multiple inheritance and enable
polymorphism across unrelated classes.

4.1 Interface Syntax and Rules


• All methods in an interface are implicitly public and abstract (Java 7 and earlier). You don't need to write
public abstract explicitly.
• All variables/fields in an interface are implicitly public, static, and final — they are constants.
• An interface cannot be instantiated directly (new Interface() → compile error).
• A class uses implements keyword to implement an interface.
• A class must implement ALL abstract methods of the interface, or declare itself abstract.
• Java 8+ additions: interfaces can have default methods (with body) and static methods.

// Interface Full Example

// Interface definition

interface Shape {

// Implicitly: public static final double PI = 3.14;

double PI = 3.14159;

// Implicitly: public abstract double area();

double area();

double perimeter();

// Java 8+: default method (has a body)

default void describe() {

[Link]("I am a shape with area = " + area());

// Class implements interface

class Circle implements Shape {

double r;

Java Programming | Packages · Interfaces · Exception Handling Page 8


Circle(double r) { this.r = r; }

public double area() { return PI * r * r; }

public double perimeter() { return 2 * PI * r; }

Circle c = new Circle(7);

[Link]("Area: " + [Link]());

[Link](); // calls default method from interface

OUTPUT:

Area: 153.93791

I am a shape with area = 153.93791

4.2 Multiple Interface Implementation


A class can implement multiple interfaces separated by commas. This is how Java achieves multiple inheritance of
TYPE (a class can behave as multiple types).

// Multiple Interface Implementation

interface Flyable { void fly(); }

interface Swimmable{ void swim(); }

// Duck implements BOTH — multiple interface implementation

class Duck implements Flyable, Swimmable {

public void fly() { [Link]("Duck flies!"); }

public void swim() { [Link]("Duck swims!"); }

// Interface can also extend another interface

interface Amphibious extends Flyable, Swimmable {

void walk(); // adds a new method

Feature Abstract Class Interface

Methods Abstract + concrete both Abstract; default/static (Java 8+)

Variables Any type allowed public static final only (constants)

Constructor Yes, has constructors No constructors

Extends/Impls extends (single) implements (multiple allowed)

Speed Slightly faster Slightly slower (older JVMs)

IS-A Yes (strong relationship) Yes (capability contract)

Use when Partial shared implementation Define contract; multiple behavior

■ Memory Trick: Interface = 100% abstract class (before Java 8). Abstract class = partially built class.

Java Programming | Packages · Interfaces · Exception Handling Page 9


■ EXAM Q: What is an interface? How is it different from an abstract class?

■ EXAM Q: Can an interface have constructors? Can it have instance variables?

■ EXAM Q: Write a program to implement multiple interfaces. (Very common!)

Java Programming | Packages · Interfaces · Exception Handling Page 10


5 EXCEPTION HANDLING – FUNDAMENTALS

DEFINITION
Formal: An exception is an abnormal event that disrupts the normal flow of a program's instructions during
execution. Exception handling is a powerful mechanism that separates error-handling code from normal business
logic, making programs more robust and maintainable. Java uses a combination of try, catch, throw, throws, and
finally keywords to manage exceptions.

Conceptual: Imagine driving a car. You normally drive on the road. But sometimes unexpected things happen —
a tire bursts (RuntimeException), you run out of fuel (IOException). If you have no plan, the car stops
permanently. Exception handling lets you plan for these unexpected situations and handle them gracefully
instead of crashing.

Why it exists: Without exception handling, even a small error (like dividing by zero or opening a missing file)
would crash the entire program. Java's exception framework lets programs detect errors, report them
meaningfully, and recover when possible.

5.1 Exception Hierarchy (Throwable Tree)


In Java, every exception is an object. All exception classes inherit from [Link]. The hierarchy is:

// Throwable Hierarchy

// Java Exception Hierarchy

[Link]

■■■ [Link] (JVM-level; do NOT catch)

■ ■■■ StackOverflowError (infinite recursion)

■ ■■■ OutOfMemoryError (heap exhausted)

■ ■■■ VirtualMachineError

■■■ [Link] (application-level)

■■■ Checked Exceptions (must handle or declare)

■ ■■■ IOException

■ ■■■ SQLException

■ ■■■ FileNotFoundException

■ ■■■ ClassNotFoundException

■■■ RuntimeException (unchecked; no must-handle)

■■■ NullPointerException

■■■ ArrayIndexOutOfBoundsException

■■■ ArithmeticException (divide by 0)

■■■ ClassCastException

Java Programming | Packages · Interfaces · Exception Handling Page 11


■■■ NumberFormatException

■■■ IllegalArgumentException

5.2 Checked vs Unchecked Exceptions


Feature Checked Exception Unchecked Exception

Also called Compile-time exception Runtime exception

Detected at Compile time Runtime

Must handle? YES — try/catch OR throws required No — optional

Inherits from Exception (not RuntimeException) RuntimeException

Examples IOException, SQLException NullPointerException, ArithmeticException

Caused by External resources (file, DB, network) Programming bugs / logic errors

5.3 Error vs Exception


Error represents a serious problem that a reasonable application should NOT try to catch — they indicate
JVM-level failures (e.g., StackOverflowError, OutOfMemoryError). Exception represents conditions that a
reasonable application might want to catch and handle.

■ Memory Trick: Checked = 'Compiler CHECKS you handle it'. Unchecked = 'You SHOULD check (but
compiler won't force you)'.

■ EXAM Q: Differentiate between checked and unchecked exceptions with examples.

■ EXAM Q: What is the difference between Error and Exception in Java?

Java Programming | Packages · Interfaces · Exception Handling Page 12


6 USING try AND catch

DEFINITION
try block: The try block encloses the code that might throw an exception. If any statement inside throws an
exception, execution immediately jumps to the matching catch block — the remaining statements in the try block
are skipped.

catch block: The catch block handles a specific type of exception. It receives the exception object as a
parameter and executes the error-handling code. A try block can have one or more catch blocks.

// try-catch Syntax

// Syntax

try {

// Code that might throw an exception

// If exception occurs here, rest of try is SKIPPED

} catch (ExceptionType e) {

// Handle the exception

// [Link]() — short description

// [Link]() — class name + message

// [Link]() — full call stack trace

// try-catch Example

public class TryCatchDemo {

public static void main(String[] args) {

int[] arr = {10, 20, 30};

try {

[Link]("Before exception");

int result = arr[0] / 0; // ArithmeticException

[Link]("This won't print"); // skipped!

} catch (ArithmeticException e) {

[Link]("Caught: " + [Link]());

[Link]("Program continues normally after catch");

OUTPUT:

Before exception

Java Programming | Packages · Interfaces · Exception Handling Page 13


Caught: / by zero

Program continues normally after catch

6.1 Flow of Execution


// Execution Flow

// Flow diagram (ASCII):

Start of try block

[Statement 1] ←■■ executes normally

[Statement 2] ←■■ THROWS exception here

■■■→ Jump to catch block

[Statement 3] ←■■ SKIPPED (never runs)

catch block executes

Code AFTER try-catch continues ←■■ normal flow resumes

6.2 Common Exception Methods


Method Returns Example Output

getMessage() Short error description / by zero

toString() Class name + message [Link]: / by zero

printStackTrace() Full stack trace to stderr Prints call chain

getClass().getName() Exception class name [Link]

getCause() The root cause Throwable null or wrapped exception

■ EXAM Q: What happens if an exception is not caught in Java?

■ EXAM Q: Can we have a try block without a catch block? (YES — if finally is present)

■ After a catch block handles the exception, the try block does NOT re-execute. Program continues AFTER
the catch.

Java Programming | Packages · Interfaces · Exception Handling Page 14


7 MULTIPLE CATCH CLAUSES

DEFINITION
Formal: A try block can be followed by multiple catch blocks, each handling a different type of exception. When
an exception is thrown, Java searches the catch blocks from top to bottom and executes the FIRST matching
catch block. After that catch executes, none of the other catch blocks run, and execution continues after the
entire try-catch structure.

Why needed: A single try block might throw different types of exceptions depending on which line executes.
Different exceptions might need different handling strategies.

CRITICAL RULE – Most Specific First!


■ EXAM TRAP – ORDERING RULE: When catching exceptions from an inheritance hierarchy, ALWAYS put
the most specific (child) exception BEFORE the more general (parent) exception. If you put Exception (the
parent of all) FIRST, it will catch everything and the specific catch blocks below it become UNREACHABLE
— causing a compile error in Java.

// Multiple catch — Correct Ordering

public class MultiCatch {

public static void main(String[] args) {

try {

String s = null;

int[] arr = new int[5];

arr[10] = 1; // ArrayIndexOutOfBoundsException

[Link](); // NullPointerException (never reaches)

int x = 5/0; // ArithmeticException (never reaches)

// Most specific first:

catch (ArrayIndexOutOfBoundsException e) {

[Link]("Array error: " + [Link]());

catch (NullPointerException e) {

[Link]("Null error: " + [Link]());

catch (RuntimeException e) { // more general

[Link]("Runtime error: " + [Link]());

catch (Exception e) { // most general — last!

[Link]("General error: " + [Link]());

Java Programming | Packages · Interfaces · Exception Handling Page 15


}

OUTPUT:

Array error: Index 10 out of bounds for length 5

7.1 Multi-Catch (Java 7+) – Catch Multiple Types in One Block


Since Java 7, you can catch multiple unrelated exception types in a single catch block using the pipe (|) operator.
This reduces code duplication when different exceptions need the same handling.

// Multi-Catch Java 7+

// Java 7+ multi-catch syntax

try {

// risky code

} catch (NullPointerException | ArithmeticException | NumberFormatException e) {

[Link]("One of three errors: " + [Link]());

// Note: e is implicitly final in a multi-catch block

// ■ WRONG ORDER — compile error:

// catch (Exception e) { } // parent

// catch (ArithmeticException e) { } // child — UNREACHABLE → compile error

■ EXAM Q: Write a program to demonstrate multiple catch blocks with the correct ordering rule.

■ EXAM Q: What happens if you put a parent exception before a child exception in catch blocks?

■ EXAM Q: What is multi-catch? When was it introduced? (Java 7)

Java Programming | Packages · Interfaces · Exception Handling Page 16


8 NESTED try STATEMENTS

DEFINITION
Formal: A try block can be placed inside another try block. This is called a nested try statement. The inner try
handles exceptions that are specific to its scope. If the inner try does not have a matching catch block for a
particular exception, the exception propagates to the outer try's catch blocks. This propagation continues up the
call stack until a handler is found, or the program terminates.

Conceptual: Think of nested try like security checkpoints. The inner checkpoint handles small issues. If it can't,
the outer checkpoint tries. If nobody catches it, the alarm (program crash) goes off.

// Nested try – Propagation Demo

public class NestedTry {

public static void main(String[] args) {

// Outer try

try {

[Link]("Outer try started");

// Inner try

try {

[Link]("Inner try started");

int[] arr = new int[3];

arr[5] = 100; // throws ArrayIndexOutOfBoundsException

} catch (ArithmeticException e) {

// Does NOT match — propagates to outer catch

[Link]("Inner catch: ArithmeticException");

// Inner catch didn't match, so outer catch fires:

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Outer catch: " + [Link]());

[Link]("After nested try");

OUTPUT:

Outer try started

Inner try started

Outer catch: Index 5 out of bounds for length 3

After nested try

Java Programming | Packages · Interfaces · Exception Handling Page 17


8.1 Exception Propagation
When an exception is thrown and not caught in the current method, it propagates to the calling method. This
continues up the call stack. If it reaches main() and is still uncaught, the JVM prints the stack trace and the
program terminates.

// Exception Propagation

class Propagation {

static void methodC() {

int x = 10 / 0; // thrown here, not caught here

static void methodB() { methodC(); // not caught here either }

static void methodA() {

try { methodB(); } // caught HERE

catch (ArithmeticException e) { [Link]("Caught in A: "+[Link]()); }

public static void main(String[] args) { methodA(); }

// Stack: main → methodA → methodB → methodC → exception

// Propagates: methodC (no catch) → methodB (no catch) → methodA (CAUGHT!)

OUTPUT:

Caught in A: / by zero

■ EXAM Q: What is exception propagation? Trace the flow with a diagram.

■ EXAM Q: Write a program with nested try blocks where the inner catch does not match and the outer catch
handles it.

Java Programming | Packages · Interfaces · Exception Handling Page 18


9 throw, throws AND finally

DEFINITION
throw: The throw keyword is used to MANUALLY throw an exception. You create an exception object and throw
it with throw new ExceptionType(). It can throw any Throwable object.

throws: The throws keyword appears in a method signature to DECLARE that the method might throw one or
more checked exceptions. It is a warning to the caller — 'this method might throw these, so you handle them.'

finally: The finally block always executes — whether an exception occurred or not, whether it was caught or not.
The only exception (pun intended): [Link]() skips finally. Used for cleanup — closing files, releasing
connections.

9.1 throw keyword


// throw keyword

class AgeValidator {

static void validateAge(int age) {

if (age < 0) {

// Manually throw an exception

throw new IllegalArgumentException("Age cannot be negative: " + age);

[Link]("Valid age: " + age);

public static void main(String[] args) {

try {

validateAge(25); // OK

validateAge(-5); // throws

} catch (IllegalArgumentException e) {

[Link]("Error: " + [Link]());

OUTPUT:

Valid age: 25

Error: Age cannot be negative: -5

9.2 throws keyword


// throws keyword

import [Link].*;

Java Programming | Packages · Interfaces · Exception Handling Page 19


class FileReader {

// Declares it may throw IOException (checked) — caller must handle

static void readFile(String path) throws IOException {

FileInputStream fis = new FileInputStream(path); // may throw

[Link]("File opened: " + path);

[Link]();

public static void main(String[] args) {

try {

readFile("[Link]");

} catch (IOException e) {

[Link]("File error: " + [Link]());

9.3 finally block


// finally block – both cases

public class FinallyDemo {

public static void main(String[] args) {

// Case 1: No exception — finally still runs

try {

[Link]("Try block");

} catch (Exception e) {

[Link]("Catch block");

} finally {

[Link]("Finally ALWAYS runs!");

[Link]("---");

// Case 2: Exception occurs — catch + finally run

try {

int x = 10/0;

} catch (ArithmeticException e) {

[Link]("Caught: " + [Link]());

} finally {

[Link]("Finally after exception too!");

Java Programming | Packages · Interfaces · Exception Handling Page 20


}

OUTPUT:

Try block

Finally ALWAYS runs!

---

Caught: / by zero

Finally after exception too!

Keyword Purpose Used in Key Point

throw Manually throw an exception Method body Followed by an exception object

throws Declare possible exceptions Method signature Warns caller of checked exceptions

finally Code that always runs try-catch block Runs even if no exception, or exception uncaught

■ EXAM TRAP: finally does NOT run if [Link]() is called inside try or catch.

■ EXAM TRAP: If both catch and finally have return statements, the finally return OVERRIDES the catch
return.

■ EXAM Q: Difference between throw and throws with examples. (VERY common!)

■ EXAM Q: Is it possible to have a try without catch? (YES — if finally is present)

■ EXAM Q: When does finally NOT execute?

Java Programming | Packages · Interfaces · Exception Handling Page 21


1 USER-DEFINED (CUSTOM) EXCEPTIONS
0

DEFINITION
Formal: A user-defined exception (also called a custom exception) is an exception class created by the
programmer by extending either Exception (for checked custom exceptions) or RuntimeException (for unchecked
custom exceptions). Custom exceptions allow developers to create meaningful, domain-specific error types that
carry relevant information about application-specific error conditions.

Conceptual: Java gives you a box of standard exceptions (NullPointerException, IOException, etc.), but what if
you need an InsufficientBalanceException for a banking app, or an InvalidStudentIdException for a university
system? You create your own! This makes your code more readable and self-documenting.

Why it exists: Standard exceptions don't cover every business scenario. Custom exceptions let you embed
domain knowledge into your error handling, making the code more descriptive and the error messages more
helpful.

10.1 Creating a Custom Exception


• Extend Exception → creates a CHECKED custom exception (caller must handle)
• Extend RuntimeException → creates an UNCHECKED custom exception (handling optional)
• Add a constructor that takes a message String and passes it to super(message)
• You can add extra fields/methods to carry more information about the error

// User-Defined Exception – Complete Example

// Step 1: Create custom exception by extending Exception

class InsufficientBalanceException extends Exception {

private double shortfall; // extra domain-specific field

InsufficientBalanceException(double shortfall) {

super("Insufficient balance! Short by: " + shortfall);

[Link] = shortfall;

public double getShortfall() { return shortfall; }

// Step 2: Use the custom exception in a class

class BankAccount {

private double balance;

BankAccount(double initial) { [Link] = initial; }

// throws declares the checked exception

void withdraw(double amount) throws InsufficientBalanceException {

if (amount > balance) {

Java Programming | Packages · Interfaces · Exception Handling Page 22


throw new InsufficientBalanceException(amount - balance);

balance -= amount;

[Link]("Withdrawn: " + amount + ". Balance: " + balance);

// Step 3: Handle the custom exception

public class CustomExceptionDemo {

public static void main(String[] args) {

BankAccount acc = new BankAccount(1000.0);

try {

[Link](500); // OK

[Link](700); // throws — only 500 left

} catch (InsufficientBalanceException e) {

[Link]("Error: " + [Link]());

[Link]("Need extra: " + [Link]());

OUTPUT:

Withdrawn: 500.0. Balance: 500.0

Error: Insufficient balance! Short by: 200.0

Need extra: 200.0

10.2 Unchecked Custom Exception


// Unchecked Custom Exception

// Unchecked custom exception — extends RuntimeException

class InvalidAgeException extends RuntimeException {

InvalidAgeException(int age) {

super("Invalid age: " + age + ". Must be 18+");

class Voter {

static void register(int age) { // NO throws needed — unchecked

if (age < 18) throw new InvalidAgeException(age);

[Link]("Registered! Age: " + age);

Java Programming | Packages · Interfaces · Exception Handling Page 23


public static void main(String[] args) {

register(20); // OK

register(15); // throws InvalidAgeException

OUTPUT:

Registered! Age: 20

Exception in thread "main" InvalidAgeException: Invalid age: 15. Must be 18+

Feature extends Exception extends RuntimeException

Type Checked Unchecked

throws needed? YES — must declare in signature NO — optional

try-catch needed? YES — caller must handle NO — optional

Best for Expected recoverable errors (DB, IO) Programming/validation errors

■ Memory Trick: Custom exception = 'Empty jar with a new label'. You extend Exception/RuntimeException
(the jar), add your message (the label), and throw it when needed.

■ EXAM Q: Write a user-defined exception class for insufficient balance / invalid age. (MOST common exam
question in this topic!)

■ EXAM Q: What is the difference between extending Exception vs RuntimeException for custom
exceptions?

■ EXAM Q: Write a program using throw, throws, and a user-defined exception together.

Java Programming | Packages · Interfaces · Exception Handling Page 24


✦ QUICK REVISION CHEAT SHEET

Concept One-liner Summary Keyword / Rule

Package Namespace for related classes; maps to folder structure package com.x.y;

Sub-package Nested package separated by dot; NOT auto-imported [Link] ≠ [Link]

[Link] Only package auto-imported; contains String, Math, etc. No import needed

import Shortcut to avoid fully qualified names import [Link];

Wildcard import Imports all classes in one package only (not sub-pkgs) import [Link].*;

Static import Import static members directly import static [Link];

private Accessible only in same class Most restrictive

default Accessible in same package No keyword; package-private

protected Same pkg + subclass (different pkg via instance only) protected

public Accessible everywhere Most permissive

Interface 100% contract; no instance, all methods public abstract interface, implements

Multiple interface Class can implement multiple interfaces (comma separated)


class A implements B,C

default method Interface method with body (Java 8+) default void method(){}

Throwable Root of exception hierarchy Error + Exception

Error JVM-level; do NOT catch StackOverflowError

Checked Must handle at compile time; IOException, SQLException extends Exception

Unchecked Runtime bugs; optional handling extends RuntimeException

try Wraps risky code; jumps to catch on exception try { }

catch Handles specific exception; most-specific FIRST catch(Type e){}

Multi-catch Catch multiple types in one block (Java 7+) catch(A | B e){}

Nested try try inside try; inner miss propagates to outer catch Exception propagation

throw Manually throw an exception object throw new Exc()

throws Declare checked exceptions in method signature void m() throws E

finally Always runs; cleanup code; skipped only on [Link]() finally{}

Custom Exception Extend Exception (checked) or RuntimeException (unchecked)


class MyEx extends Exc

END OF UNIT III NOTES — Best of Luck! Study Smart, Ace the Exam! ■

Java Programming | Packages · Interfaces · Exception Handling Page 25

You might also like