Menu

Java Topic

Java Exceptions

Exceptions in Java are events that disrupt the normal flow of the program's execution. They are used to handle errors and other exceptional conditions that may occur during the runtime of a program. Java provides a robust mechanism for managing exceptions through its exception-handling framework.

1. Exception Hierarchy

Java's exception hierarchy is rooted in the Throwable class, which has two main subclasses:

  • Error: Represents serious issues that a reasonable application should not try to catch (e.g., OutOfMemoryError).
  • Exception: Represents conditions that a program should catch (e.g., IOException, SQLException).

2. Try-Catch Block

To handle exceptions, you use a try-catch block. The code that might throw an exception is placed inside the try block, and the code to handle the exception is placed inside the catch block:

public class TryCatchExample {
    public static void main(String[] args) {
        int result = 0;
        try {
            result = 10 / 0; // This will throw an ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
        System.out.println("Result: " + result);
    }
}

This example demonstrates handling an ArithmeticException that occurs due to division by zero.

3. Finally Block

The finally block is used for code that must execute regardless of whether an exception is thrown or not. It's typically used for resource cleanup (e.g., closing files or releasing resources):

public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Trying to execute code...");
            int result = 10 / 0; // This will throw an ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed.");
        }
    }
}

This example shows that the finally block executes even if an exception is caught.

4. Throwing Exceptions

You can throw exceptions manually using the throw keyword. This is useful for indicating that a method has encountered an issue:

public class ThrowExceptionExample {
    public static void validateNumber(int number) {
        if (number < 0) {
            throw new IllegalArgumentException("Number cannot be negative.");
        }
    }

    public static void main(String[] args) {
        try {
            validateNumber(-1);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}

This example demonstrates how to throw and catch a custom exception.

5. Custom Exceptions

You can create custom exception classes by extending the Exception class or one of its subclasses:

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

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            throw new CustomException("This is a custom exception.");
        } catch (CustomException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}

This example demonstrates how to define and use a custom exception class.

Java Wrapper Classes

In Java, wrapper classes are used to convert primitive data types into objects. Each primitive type has a corresponding wrapper class in the java.lang package. These classes provide a way to treat primitive types as objects and are often used in collections that require objects, such as ArrayList or HashMap.

1. Wrapper Classes Overview

Here are the wrapper classes for each primitive data type:

  • byte - Byte
  • short - Short
  • int - Integer
  • long - Long
  • float - Float
  • double - Double
  • char - Character
  • boolean - Boolean

2. Autoboxing and Unboxing

Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class, and unboxing is the reverse process. Java handles these conversions automatically, making it easy to use primitive types and wrapper classes interchangeably.

public class AutoboxingUnboxing {
    public static void main(String[] args) {
        int primitiveInt = 10;
        Integer wrapperInt = primitiveInt; // Autoboxing

        Integer anotherWrapperInt = new Integer(20);
        int anotherPrimitiveInt = anotherWrapperInt; // Unboxing

        System.out.println("Wrapper Integer: " + wrapperInt);
        System.out.println("Primitive int: " + anotherPrimitiveInt);
    }
}

This example shows how Java performs autoboxing and unboxing automatically.

3. Common Methods

Wrapper classes provide various utility methods for converting and manipulating data:

  • parse(String s): Parses the string argument as a type and returns its value (e.g., Integer.parseInt("123")).
  • valueOf( value): Returns an instance of the wrapper class with the specified value (e.g., Integer.valueOf(100)).
  • toString(): Returns the string representation of the object (e.g., Integer.toString(123)).
public class WrapperMethods {
    public static void main(String[] args) {
        String numberString = "456";
        int parsedInt = Integer.parseInt(numberString);
        Integer wrappedInt = Integer.valueOf(parsedInt);

        System.out.println("Parsed int: " + parsedInt);
        System.out.println("Wrapped Integer: " + wrappedInt);
        System.out.println("String representation: " + wrappedInt.toString());
    }
}

This example demonstrates how to use common methods from wrapper classes to parse strings, convert between types, and get string representations.

4. Comparison and Equality

Wrapper classes also provide methods for comparing values:

  • compareTo( o): Compares this object with the specified object for order.
  • equals(Object obj): Compares this object with the specified object for equality.
public class WrapperComparison {
    public static void main(String[] args) {
        Integer num1 = new Integer(30);
        Integer num2 = new Integer(40);

        System.out.println("Comparison result: " + num1.compareTo(num2));
        System.out.println("Equality check: " + num1.equals(num2));
    }
}

This example demonstrates comparing and checking equality of wrapper class instances.

 

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?