How to Create Custom Exceptions in Java

How to create a custom exception type in Java?

You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception
{
// Parameterless Constructor
public WordContainsException() {}

// Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}

Usage:

try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
// Process message however you would like
}

Java create custom exception class with specific status code

In case you want to have global exception handling for your API, and prefer to have custom error responses, you can add @ControllerAdvice:

@ControllerAdvice
public class ApiExceptionHandler {

@ExceptionHandler({ ApiException.class })
protected ResponseEntity<ApiErrorResponse> handleApiException(ApiException ex) {
return new ResponseEntity<>(new ApiErrorResponse(ex.getStatus(), ex.getMessage(), Instant.now()), ex.getStatus());
}
}

// you can put any information you want in ApiErrorResponse
public class ApiErrorResponse {

private final HttpStatus status;
private final String message;
private final Instant timestamp;

public ApiError(HttpStatus status, String message, Instant timestamp) {
this.status= status;
this.message = message;
this.timestamp = timestamp;
}

public HttpStatus getStatus() {
return this.status;
}

public String getMessage() {
return this.message;
}

public Instant getTimestamp() {
return this.timestamp;
}
}

// your custom ApiException class
public class ApiException extends RuntimeException {

private final HttpStatus status;

public ApiException(HttpStatus status, String message) {
super(message);
this.status = status;
}

public HttpStatus getStatus() {
return this.status;
}
}

Can I define multiple custom exceptions in java in a single class file and invoke them via methods?

Generally custom exceptions should be defined in the top level. Because, almost universally, these exceptions are part of the interface of the package or module.

If the user cannot see them, then how are they going to catch them separately? And if you don't want to catch them separately, then why would you need separate classes?

However, if you must, you can include them into a class for which they are required:

public class SeatReservationSystem {
public static class ReservationFailedException {
... constructors taking a message ...
}

public static class SeatTakenException extends ReservationFailedException {
... constructors taking a message ...
}

public static class OutsideAgeException extends ReservationFailedException {
... constructors taking a message ...
}

....
}

After that you can create any method that returns them as required. Don't create methods that throw them as the compiler won't see those as exit points of the block you're in, and you'll get strange situations.

Here is some code to show what I mean:

// wrong
public static void throwRuntimeException() throws RuntimeException {
throw new RuntimeException();
}

// correct, but dangerous
public static RuntimeException createRuntimeException() {
return new RuntimeException();
}

public static void main(String[] args) {
String initializeMeOrThrowException;
if (new Random().nextBoolean()) {
// compiler doesn't recognize that the method always throws an exception
throwRuntimeException();

// this the compiler can understand, there is an explicit throw here:
// throw createRuntimeException();

// but this is the pitfall, it doesn't do anything:
// createRuntimeException();
} else {
initializeMeOrThrowException = "Initialized!";
}

// Compiler error for throwRuntimeException and createRuntimeException without throws:
// "The local variable initializeMeOrThrowException may not have been initialized"
System.out.println(initializeMeOrThrowException);
}

However, experience learns me that I forget the throws statement for the throw createException(...); method, and the stupid compiler doesn't warn me about that (even though the statement is utterly useless without it). So I try and not use either.


Note that I'm not certain if you should use exceptions for this. If your system is a reservation system, then refusing tickets is not that exceptional. Returning a ReservationResult makes more sense.

How to create a custom exception which wraps mutliple exceptions in java

In the spirit of the question as asked:

You would have to catch the various exceptions within your method, and then throw a CustomException from your catch block. The ability for an exception to "wrap" around another exception is built in via the Exception class itself (see the Exception(Throwable cause) constructor).

public void method() throws IOException, CustomException {
try {
//Body of the method
} catch (IllegalArgumentException | InstantiationException | IllegalAccessException e) {
throw new CustomException(e);
}
}

That said, IllegalArgumentException is not a checked exception, so you wouldn't have to declare it anyway.

Also worth pointing out, the above is based on you specifying that you want to create a custom exception. Another option is to declare in your throws clause some type that is a common base class of the various checked exceptions that might actually be thrown. For example, both of the checked exceptions in your list are subclasses of ReflectiveOperationException, so you could just say

public void method() throws IOException, ReflectiveOperationException {
//Body of the method
}

The trade-off, of course, is that you're not being as informative to those writing code that calls your method, so that may limit the quality of their exception handlers. In the extreme, you could just say throws Thorwable, but this is pretty poor form.

Creating custom exception in java in a single class is bad practice?

Best practice is to have the custom exceptions classes outside the main code, better in separate files

public class Test {
static String s1, s2 = null;

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter diection of first vehicle");
s1 = sc.nextLine();
System.out.println("enter direction of second vehicle");
s2 = sc.nextLine();
try {
if (s1.equals(s2)) {
System.out.println("everything is fine no exception");
} else {
if (s1.equals("FOO")) {
throw new IncorrectWord("Foo is an incorrect word");
} else {
throw new Collision();
}
}
} catch (Collision | IncorrectWord e) {
System.out.println("this is a exception ");
}
sc.close();
}
}

Errors, put it in separate files

class Collision extends Exception {
}

class IncorrectWord extends Exception {
public IncorrectWord(String errorMessage) {
super(errorMessage);
}
}

Creating custom java exception

This should help you for scanning Integer values.

try{
System.out.print("Enter an integer: ");
int number = input.nextInt();
}
catch (InputMismatchException ex) {
System.out.println("Incorrect input: an integer is required)");
//It's also possible to throw your custom Exception here, like "throw new CustomException();"
}

About the IndexOutOfBoundsException, just write a try catch block around the area, where you expect that exception and throw your own custom exception.

try{
...
}catch(IndexOutOfBoundsException e){
throw CustomException2();
}

On creating custom exceptions

Exceptions are just classes that extend class Throwable. Defining your own exception is done by creating a class that extends Throwable or one of its subclasses.

You can throw your own exception using throw new myError();.

ArithmeticException is a special exception thrown by the JVM when you divide by zero. It's not the exception that is looking for places where you divide by zero; it's how the / works. The / operator checks if the denominator is zero and will then throw the exception.

There is no way to add for example a check to the + operator so that it will throw whatever exception if the result of adding two numbers is zero. You'd have to write your own method to check and do this.

public int add(int a, int b) {
int result = a + b;
if (result == 0) {
throw new myError();
}
return result;
}

// Then use the add() method instead of +
try {
int a = 1;
int b = -1;
int result = add(a, b);
System.out.println(result);
} catch (myError e) {
System.out.println("The result was zero!");
}


Related Topics



Leave a reply



Submit