How to Write Custom Exceptions

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
}

Proper way to declare custom exceptions in modern Python?

Maybe I missed the question, but why not:

class MyException(Exception):
pass

To override something (or pass extra args), do this:

class ValidationError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super().__init__(message)

# Now for your custom code...
self.errors = errors

That way you could pass dict of error messages to the second param, and get to it later with e.errors.

In Python 2, you have to use this slightly more complex form of super():

super(ValidationError, self).__init__(message)

When should I declare custom exceptions?

There are two questions merged into one: How often should I use custom exceptions (to not overuse them)? and Should I actually ever prefer custom exceptions (to the builtin ones)? Let's answer both.

Custom exception overusing

The blog post from Dan Bader you linked is a great example of how it should not be done. An example of overusing of custom exceptions. Every exception class should cover a group of related uses (ConfigError, BrowserError, DateParserError). You definitely shouldn't create a new custom exception for every particular situation where something needs to be raised. That's what exception messages are for.

Custom vs. builtin exceptions

This is a more opinion-based topic and it also highly depends on the particular code scenario. I will show two interesting examples (out of possibly many) where I consider using a custom exception can be beneficial.

01: Internals exposure

Let's create a simple web browser module (a thin wrapper around the Requests package):

import requests

def get(url):
return requests.get(url)

Now imagine you want to use your new web browser module in several modules across your package. In some of them you want to catch some possible network related exceptions:

import browser
import requests

try:
browser.get(url)
except requests.RequestException:
pass

The downside of this solution is that you have to import the requests package in every module just to catch an exception. Also you are exposing the internals of the browser module. If you ever decide to change the underlying HTTP library from Requests to something else, you will have to modify all the modules where you were catching the exception. An alternative to catch some general Exception is also discouraged.


If you create a custom exception in your web browser module:

import requests

class RequestException(requests.RequestException):
pass

def get(url):
try:
return requests.get(url)
except requests.RequestException:
raise RequestException

then all your modules will now avoid having the disadvantages described above:

import browser

try:
browser.get(url)
except browser.RequestException:
pass

Notice that this is also exactly the approach used in the Requests package itself - it defines its own RequestException class so you don't have to import the underlying urllib package in your web browser module just to catch the exception it raises.

02: Error shadowing

Custom exceptions are not just about making code more nice. Look at (a slightly modified version of) your code to see something really evil:

def validate(name, value):
if len(name) < int(value):
raise ValueError(f"Name too short: {name}")

return name

Now someone will use your code but instead of propagating your exception in case of a short name he would rather catch it and provide a default name:

name = 'Thomas Jefferson'

try:
username = validate(name, '1O')
except ValueError:
username = 'default user'

The code looks good, doesn't it? Now watch this: If you change the name variable to literally any string, the username variable will always be set to 'default user'. If you defined and raised a custom exception ValidationError, this would not have happened.

Laravel create custom exception with parameters & return as JSON

In your case you are returning the exception as a response instead of throwing it. That's why it's displayed like this.

You could just have to throw the exception without the try/catch:

$check_api_key = $attendance_libraries->check_api_key($this->request);

if ($check_api_key == null) {
throw new NullException(false, 'API Key Not Found', null, 500);
}

The laravel error handler will catch the exception & render it.

EDIT: Or as @miken32 pointed out you could re throw the exception to handle other exceptions:

try {
//...
} catch (NullException $e) {
throw $e;
} catch (// other exceptions) {
}

Sample Image

How to write a custom exception class derived from std::invalid_argument?

I solved this problem based on the feedback that I received from others through comments and answers. So I decided to leave my own answer/solution here for future readers.

Below can be seen what I came up with after much thought and research. This solution is fairly simple and readable.

Here is the exception class interface:

Foo_Exception.h

#include <exception>

class Foo_Exception : public std::invalid_argument
{
public:
explicit Foo_Exception( const std::string& what_arg );
};

And here is its implementation:

Foo_Exception.cpp

#include "Foo_Exception.h"

Foo_Exception::Foo_Exception( const std::string& what_arg )
: std::invalid_argument( what_arg )
{
}

A function that throws Foo_Exception:

Bar.cpp

#include "Bar.h"
#include "Foo_Exception.h"

void setCharacter( const char& c )
{
if ( /* an invalid character (c) is passed to setCharacter */ )
{
std::string exceptionMsg;
exceptionMsg.reserve( 130000 );

exceptionMsg = "A string literal to be appended, ";
exceptionMsg += std::to_string( /* a constexpr int */ );
exceptionMsg += /* a char from a const unordered_set<char> */;

throw Foo_Exception( exceptionMsg );
}

/*
rest of the code
*/
}

How to handle the exception:

main.cpp

#include <iostream>
#include "Bar.h"
#include "Foo_Exception.h"

int main( )
{
try
{
setCharacter( '-' ); // The dash character is not valid! Throws Foo_Exception.
}
catch ( const Foo_Exception& e )
{
std::cerr << e.what( ) << '\n';
}

return 0;
}

Summary of the Changes:

  1. Notice how there's no need for a what() function since the compiler generates it implicitly because Foo_Exception inherits from std::invalid_argument.

  2. Also, the process of creating the exception message was moved from the Foo_Exception's ctor to the body of the function setCharacter which actually throws the aforementioned exception. This way, the Foo_Exception's ctor is not responsible for creating the message. Instead, it is created in the body of the function that throws and is then passed to the ctor of Foo_Exception to initialize the new exception object.

  3. The data member std::string Exception_Msg was also removed from Foo_Exception as it wasn't needed anymore.

  4. Finally, the try-catch block was moved to main() so that it now wraps around setCharacter() and catches a Foo_Exception object that it might throw.

Final word:
Any suggestions to further improve my answer is highly appreciated.
Thanks a ton for all the feedback.

C#, usage of custom exceptions

While normally I'd suggest that a question like this should be closed as opinion-based, in this case there's really clear guidance from Microsoft:

Use the predefined .NET exception types

Introduce a new exception class only when a predefined one doesn't apply. For example:

  • Throw an InvalidOperationException exception if a property set or method call is not appropriate given the object's current state.

  • Throw an ArgumentException exception or one of the predefined classes that derive from ArgumentException if invalid parameters are passed.

In other words, your customer is asking you to go against guidance from the platform authors.

You may not be able to change the customer's mind to follow the guidance, but you can be confident that your approach is the recommended one, and their approach goes against that.

Following conventions like this is particularly important in Open Source projects - it's one thing to decide that you'll have your own conventions when only your team will work with the code, but if an application uses 10 different Open Source libraries, each of which has decided to create its own conventions, that's a nightmare.

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 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.

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.



Related Topics



Leave a reply



Submit