Understanding Packages, Access Modifiers, and Exception Handling in Java

Markdown

View as Markdown

As Java applications become larger and more complex, organizing code efficiently and handling errors effectively become increasingly important. Java provides packages to organize classes, access modifiers to control visibility, and exception handling mechanisms to manage runtime errors gracefully.

In this article, you'll learn how to create and use packages, understand Java's access modifiers, and handle exceptions using try, catch, finally, throw, and throws.

Learning Objectives

  • Understand the purpose of packages in Java.

  • Create and use built-in and user-defined packages.

  • Apply access modifiers appropriately.

  • Handle exceptions using Java's exception handling mechanisms.

  • Create custom exceptions.

  • Write reliable and maintainable Java programs.

What are Packages?

A package is a collection of related classes and interfaces that helps organize Java programs. Packages improve code maintainability, avoid naming conflicts, and provide access protection.

Java provides:

  • Built-in packages

  • User-defined packages

Built-in Packages

Java includes numerous built-in packages that provide ready-to-use classes and methods.

Some commonly used packages include:

Package

Purpose

java.lang

Core Java classes

java.util

Collections, Scanner, Date classes

java.io

File handling operations

java.sql

Database connectivity

java.time

Date and time operations

java.math

Mathematical operations

 Example

import java.util.Scanner;

public class ScannerExample {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter your name:");

        String name = input.nextLine();

        System.out.println("Welcome " + name);

    }

}

User-Defined Packages

Developers can create their own packages to organize applications.

Syntax

package packageName;

Example

package student;

public class Student {

    public void display() {

        System.out.println("Welcome to Java.");

    }

}

The package name is written at the beginning of the Java file.

Importing Packages

The import statement allows us to access classes from other packages.

Syntax

import packageName.className;

Example

import java.util.Scanner;

To import all classes from a package:

import java.util.*;

Static Import

Static import allows us to access static members without using the class name repeatedly.

Example

Without static import:

System.out.println(Math.sqrt(25));

Using static import:

import static java.lang.Math.*;

public class Example {

    public static void main(String[] args) {

        System.out.println(sqrt(25));

    }

}

Output

5.0

Understanding Access Modifiers

Access modifiers determine the visibility and accessibility of classes, variables, constructors, and methods.

Java provides four access modifiers:

  • public

  • private

  • protected

  • default

public Access Modifier

Members declared as public are accessible from anywhere in the application.

Example

public class Student {

    public String name = "John";

}

The variable can be accessed from any class.

private Access Modifier

Members declared as private are accessible only within the same class.

Example

public class Student {

    private int marks = 90;

}

Private members are commonly accessed using getter and setter methods.

protected Access Modifier

Protected members are accessible:

  • Within the same package.

  • By subclasses outside the package.

Example

protected String department = "IT";

Protected members are particularly useful when implementing inheritance.

Default Access Modifier

When no access modifier is specified, Java assigns the default access level.

Default members are accessible only within the same package.

 

Example

class Student {

    String course = "Java Programming";

}

Access Modifier Comparison

Access Modifier

Same Class

Same Package

Subclass

Different Package

public

Yes

Yes

Yes

Yes

protected

Yes

Yes

Yes

Limited Access

default

Yes

Yes

No

No

private

Yes

No

No

No

 

What is an Exception?

An exception is an unexpected event that occurs during program execution and disrupts the normal flow of the program.

Examples include:

  • Dividing by zero

  • Invalid user input

  • File not found errors

  • Database connection failures

Java provides built-in mechanisms to handle exceptions gracefully.

Types of Exceptions

Java exceptions are broadly classified into:

  • Checked Exceptions

  • Unchecked Exceptions

Checked Exceptions

These exceptions are checked during compilation.

Examples include:

  • IOException

  • SQLException

  • FileNotFoundException

Unchecked Exceptions

These occur during runtime.

Examples include:

  • ArithmeticException

  • NullPointerException

  • ArrayIndexOutOfBoundsException

  • NumberFormatException

Using try and catch

The try block contains code that may generate an exception, while the catch block handles it.

Example

public class ExceptionExample {

    public static void main(String[] args) {

        try {

            int result = 10 / 0;

            System.out.println(result);

        }

        catch (ArithmeticException e) {

            System.out.println("Cannot divide by zero.");

        }

    }

}

Output

Cannot divide by zero.

Using finally

The finally block always executes regardless of whether an exception occurs.

Example

public class FinallyExample {

    public static void main(String[] args) {

        try {

            System.out.println("Inside Try Block");

        }

        finally {

            System.out.println("Finally Executed");

        }

    }

}

Output

Inside Try Block

Finally Executed

The finally block is commonly used for:

  • Closing files

  • Releasing database connections

  • Cleaning up resources

Using throw

The throw keyword explicitly generates an exception.

Example

public class ThrowExample {

    public static void main(String[] args) {

        int age = 15;

        if(age < 18) {

            throw new ArithmeticException("Age must be 18 or above.");

        }

    }

}

Using throws

The throws keyword indicates that a method may generate an exception.

Example

import java.io.IOException;

public class Example {

    public static void display() throws IOException {

        // Exception handling code

    }

}

The calling method becomes responsible for handling the exception.

Creating Custom Exceptions

Java allows developers to create their own exceptions.

Example

class InvalidAgeException extends Exception {

    public InvalidAgeException(String message) {

        super(message);

    }

}

Using the custom exception:

if(age < 18) {

    throw new InvalidAgeException(

            "Invalid Age");

}

Custom exceptions improve application readability and error reporting.

Real-World Applications

Packages, access modifiers, and exception handling are widely used in:

  • Banking applications

  • Hospital management systems

  • E-commerce platforms

  • Student information systems

  • Enterprise software development

  • Database-driven applications

These concepts help developers build secure, scalable, and reliable applications.

 

Common Mistakes

Avoid these common errors:

  • Forgetting to import required packages.

  • Using inappropriate access modifiers.

  • Leaving exceptions unhandled.

  • Catching overly generic exceptions unnecessarily.

  • Ignoring resource cleanup operations.

  • Using throw and throws interchangeably.

Practice Exercise

Write Java programs to:

  1. Import and use the Scanner class.

  2. Create a user-defined package.

  3. Demonstrate all four access modifiers.

  4. Handle division-by-zero exceptions using try and catch.

  5. Demonstrate the use of the finally block.

  6. Create and use a custom exception.

  7. Implement methods that use the throws keyword.

  8. Use static import with mathematical operations.

Was this article helpful?

Still need help?

Contact us