Tasks studies - laboratory
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:
try
: Defines a block of code monitored for errors.catch
: Used with try
to catch specific exceptions and handle them appropriately.throw
: Signals the occurrence of a specific exception.throws
: Specifies which exceptions a method can throw.finally
: Defines a block of code executed regardless of whether an exception occurred in the try
block.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
}
Throwable
: Superclass of all exceptions.Exception
: Exceptions that can be caught and handled by user programs.Error
: Exceptions representing severe issues in the runtime environment, which cannot be handled by user programs.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 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");
}
}
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");
}
}
}
The Throwable
class overrides the toString()
method to display exception descriptions.
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception: " + e);
}
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());
}
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");
}
}
}
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);
}
}
}
finally
BlockThe 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();
}
}
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.
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.
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.
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()
.
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.