Java throw exception in spring boot with message and getter setter

www‮uttual.‬ri.com
Java throw exception in spring boot with message and getter setter

In Spring Boot, you can throw an exception to indicate that an error or exceptional condition has occurred during the execution of your application. To throw an exception with a message and getter/setter methods, you can create a custom exception class that extends the RuntimeException class and defines the necessary fields and methods.

Here's an example of how you can create a custom exception class in Spring Boot:

public class MyException extends RuntimeException {
  private int code;
  private String message;

  public MyException(int code, String message) {
    this.code = code;
    this.message = message;
  }

  public int getCode() {
    return code;
  }

  public void setCode(int code) {
    this.code = code;
  }

  @Override
  public String getMessage() {
    return message;
  }

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

In this example, the MyException class extends the RuntimeException class and defines an int field for the code and a String field for the message. It also provides getter and setter methods for these fields.

To throw an instance of this exception, you can use the throw keyword and pass the necessary arguments to the exception's constructor:

if (value < 0) {
  throw new MyException(400, "Value must be non-negative");
}

The exception can then be caught and handled using a try-catch block. You can access the code and message fields of the exception using the getter methods:

try {
  // code that may throw an exception
} catch (MyException e) {
  int code = e.getCode();
  String message = e.getMessage();
  // handle the exception
}

It's important to note that the RuntimeException class is a subclass of the Exception class and is not checked by the compiler. This means that you do not need to declare that your method throws the exception or handle it in a try-catch block. However, it is generally good practice to handle exceptions to ensure that your application is robust and can recover from errors.

Created Time:2017-10-17 20:18:53  Author:lautturi