Programming Java

Tasks studies - laboratory


Project maintained by dawidolko Hosted on GitHub Pages — Theme by dawidolko

Lab11 - Exception Handling and Throwing in Java

Exceptions are abnormal situations that occur during program execution. Languages without exception handling mechanisms require manual error detection and management, often through error codes. Java provides special constructs to detect and handle such situations. An exception in Java is an object describing an exceptional (erroneous) situation that occurred in the program.

When an error occurs in a method, an exception is thrown describing the error. The method can handle the exception itself or pass it on. Finally, the error is caught and handled appropriately.

Java uses the following keywords for exception handling:

Below is an example of a try/catch/finally block for handling three types of exceptions:

try {
  // Code monitored for errors
} catch (FirstTypeException e) {
  // Handling the first type of exception
} catch (SecondTypeException e) {
  // Handling the second type of exception
} catch (ThirdTypeException e) {
  // Handling the third type of exception
} finally {
  // Code executed before the method ends
}

Exception Hierarchy


Default Exception Handling

If the system detects an operation like division by zero, it creates an exception object. If no custom handling is provided, the exception is caught by the default handler, which displays a stack trace and terminates the program.

Example:

class DivisionException {
  static void divide(int dividend, int divisor) {
    int result = dividend / divisor;
  }

  public static void main(String[] args) {
    DivisionException.divide(1024, 0);
  }
}

Custom Exception Handling

Custom exception handling allows correcting errors and preventing premature program termination.

Example:

class CustomExceptionHandling {
  public static void main(String[] args) {
    int dividend, divisor, result;
    try {
      dividend = 128;
      divisor = 0;
      result = dividend / divisor;
      System.out.println("This won't execute!");
    } catch (ArithmeticException e) {
      System.out.println("Division by zero!");
    }
    System.out.println("After the exception");
  }
}

Order of Exception Handling

When multiple catch blocks are used, subclass exceptions must appear before superclass exceptions. The following code is incorrect and needs correction:

Incorrect code:

class SubclassException {
  public static void main(String[] args) {
    try {
      int result = 224 / 0;
    } catch (Exception e) {
      System.out.println("Generic Exception");
    } catch (ArithmeticException e) {
      System.out.println("Unreachable code");
    }
  }
}

Displaying Exception Descriptions

The Throwable class overrides the toString() method to display exception descriptions.

try {
  int x = 10 / 0;
} catch (ArithmeticException e) {
  System.out.println("Exception: " + e);
}

Catching Any Exception

Handling a general exception of the base class Exception is possible. Useful methods in the Throwable class include String getMessage().

Example:

catch (Exception e) {
  System.out.println("Exception: " + e.getMessage());
}

Throwing Exceptions

Programs can explicitly throw exceptions using the throw keyword. The object must be of the Throwable class or its subclass.

Example:

class ThrowDemo {
  static void method() {
    try {
      throw new NullPointerException("demo");
    } catch (NullPointerException e) {
      System.out.println("Caught in method");
      throw e; // Re-throwing the exception
    }
  }

  public static void main(String[] args) {
    try {
      method();
    } catch (NullPointerException e) {
      System.out.println("Caught again");
    }
  }
}

Declaring Exceptions with throws

If a method can cause an exception it cannot handle, it must declare it using throws.

class ThrowsExample {
  static void method() throws IllegalAccessException {
    throw new IllegalAccessException("demo");
  }

  public static void main(String[] args) {
    try {
      method();
    } catch (IllegalAccessException e) {
      System.out.println("Caught: " + e);
    }
  }
}

The finally Block

The finally block is executed regardless of whether an exception occurred.

Example:

class FinallyDemo {
  static void procA() {
    try {
      System.out.println("Inside procA");
      throw new RuntimeException("demo");
    } finally {
      System.out.println("procA: finally");
    }
  }

  static void procB() {
    try {
      System.out.println("Inside procB");
      return;
    } finally {
      System.out.println("procB: finally");
    }
  }

  static void procC() {
    try {
      System.out.println("Inside procC");
    } finally {
      System.out.println("procC: finally");
    }
  }

  public static void main(String[] args) {
    try {
      procA();
    } catch (Exception e) {
      System.out.println("Exception caught");
    }
    procB();
    procC();
  }
}

Tasks

Task 1

Create a class WprowadzZKonsoli with methods to input different data types (e.g., int, byte, double, BigDecimal) while handling exceptions for invalid inputs like “1w2”. Use the Scanner class.


Task 2

Write a program storing 10 names in a string array. Let the user input an index to display the name. If the index is out of range, handle the exception and continue. End the loop when the user enters -1 or invalid data.


Task 3

Evaluate the results of these expressions:

a) double x = 2.0 / 0.0;
b) float y = 2.0f / 0f;
c) int z = 2 / 0;

Which expressions throw exceptions? State the type of exception.


Task 4

a) Create a custom exception DivisionByZeroException inheriting from ArithmeticException. Override getMessage() to include the method name causing the exception.

b) Test DivisionByZeroException by creating methods DivisionD and DivisionF for dividing double and float, respectively.

c) Catch the exception in DivisionD and use the overridden getMessage().


Task 5

a) Create a custom exception NegativeNumberException for invalid negative values in fields like age, weight, and height.

b) Create a class Osoba with fields name, surname, age, weight, and height. Implement getters, setters, and a constructor. Throw NegativeNumberException for negative values and NullPointerException for null values.

c) Test the Osoba class with invalid inputs, catch exceptions, and handle them.