How to Define Custom Exception Class in Java, the Easiest Way

How to define custom exception class in Java, the easiest way?

No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message) in your constructor to invoke your parent constructor. For example, like this:

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

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.

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);
}
}

Best way to add the custom exception for the spring boot code

Here are some of approaches you can follow to handle your custom exceptions.

Create a POJO to handle your custom error messages and put your properties you want to return.

public class ErrorResponse {
private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}

Approach 1. Within your Controller method.

    @RequestMapping("/car/{id}")
public ResponseEntity<?> getCar(@PathVariable String id) {
Car car = carService.getCar(id);
if (car == null) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage("Record not found");
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND)
}
return new ResponseEntity<>(car, HttpStatus.OK);
}

Approach 2: Handle exceptions globally.

Step 1: Create NotFound exception class and extend to RunTime Exception.

public class NoRecordFoundException extends RuntimeException {

public NoRecordFoundException() {
super();
}
}

Step 2: Create Global Exception handler

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(NoRecordFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public ErrorResponse handleNoRecordFoundException(NoRecordFoundException ex)
{

ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage("No Record Found");
return errorResponse;
}

//same you can handle Exceptionerror for internal

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorResponse handleDefaultException(Exception ex) {
ErrorResponse response = new ErrorResponse();
response.setMessage(ex.getMessage());
return response;
}
}

Step 3: throw Not found exception from your controller or service:

        @RequestMapping("/car/{id}")
public ResponseEntity<?> getCar(@PathVariable String id) {
Car car = carService.getCar(id);
if (car == null) {
throw new NoRecordFoundException();
}
return new ResponseEntity<>(car, HttpStatus.OK);
}

Approach 3: Create @ExceptionHandler within controller and throw

 @ExceptionHandler(NoRecordFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public ErrorResponse handleNoRecordFoundException(NoRecordFoundException ex) {

ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage("No Record Found");
return errorResponse;
}

How do I custom make an exception?

package example.stackoverflow;

import java.util.Scanner;

public class AgeChecker
{
public static final int MIN_AGE = 0;
public static final int MAX_AGE = 125;

static class InvalidAgeException extends Exception
{
private static final long serialVersionUID = 1340715735048104509L;

public InvalidAgeException()
{ }

public InvalidAgeException(String message)
{
super(message);
}

public InvalidAgeException(String message, Throwable cause)
{
super(message, cause);
}
}

public static void main(String[] args)
{
Scanner inputdata = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = inputdata.nextLine();
System.out.print(name+", enter your age: ");
int age = inputdata.nextInt();
try
{
System.out.println("You entered: "+age);
// Assuming age limits are non-inclusive
if( (age <= MIN_AGE) || (age >= MAX_AGE) )
{
throw new InvalidAgeException("Out of range error! (must be between ages 0 and 125)");
}
}
catch(InvalidAgeException e)
{
e.printStackTrace();
}
finally
{
System.out.println("Age Checking Complete.");
if(inputdata != null)
{
inputdata.close();
}
}
}
}

Also note that you need to close() your Scanner whenever you're done with it. It is often useful to do such cleanup in a finally block, so that's where I've put it in this example.



Related Topics



Leave a reply



Submit