This repository has been archived. Please use err-java instead, which provides a similar implementation.
The exception class with reason.
In Java programming, it's quite cumbersome to define exception classes for various exception cases. However, handling multiple exception cases with one exception class can make it difficult to identify specific cases.
The ReasonedException class provided by this package resolves these issues by
accepting a Record object representing the reason as an argument.
Since the Record class can be defined with minimal implementation, defining a
Record class for each exception case and passing it to ReasonedException
enables to create exception objects that can identify the specific exception
cases.
In addition, the Record class allows to define fields, their getters, and
constructors without need for cumbersome implementation.
This means that a Record object as a reason can hold the values of variables
representing the situation when an exception occurs.
This package can be installed from Maven Central Repository.
The examples of declaring that repository and the dependency on this package in
Maven pom.xml and Gradle build.gradle are as follows:
<dependencies>
<dependency>
<groupId>io.github.sttk</groupId>
<artifactId>reasonedexception</artifactId>
<version>0.3.1</version>
</dependency>
</dependencies>
repositories {
mavenCentral()
}
dependencies {
implementation 'io.github.sttk:reasonedexception:0.3.1'
}
The following code creates a ReasonedException and throws it.
public class SampleClass {
record IndexOutOfRange(int index, int min, int max) {}
public void sampleMethod() throws ReasonedException {
...
throw new ReasonedException(InvalidOutOfRange(i, 0, array.length));
}
}
And the following code catches the exception and identifies the reason with a switch expression.
try {
sampleMethod();
} catch (ReasonedException e) {
switch (e.getReason()) {
case IndexOutOfRange r -> {
int index = r.index();
int min = r.min();
int max = r.max();
...
}
...
}
}
This library supports native build with GraalVM.
See the following pages to setup native build environment on Linux/macOS or Windows.
And see the following pages to build native image with Maven or Gradle.
NOTE: If serialization for ReasonedException is used, it is needed to
specify to specify the serialization settings for derived classes of Record
indicating the reason and derived classes of Throwable indicating the causing
exception classes in the serialization-config.json file.
This framework supports JDK 21 or later.
- GraalVM CE 21.0.2+13.1 (openjdk version 21.0.2)
- GraalVM CE 22.0.1+8.1 (openjdk version 22.0.1)
Copyright (C) 2024 Takayuki Sato
This program is free software under MIT License.
See the file LICENSE in this distribution for more details.