0

In an interview, I was recently asked the following question:

Is there any other way of creating custom Exception without using extends:

  1. extending Exception class or sub class of Exception for checked exception
  2. extending RuntimeException or sub class of RuntimeException for unchecked exception.

What would be the possible answer to give?

Bentaye
  • 9,403
  • 5
  • 32
  • 45
surya prakash
  • 49
  • 1
  • 5

7 Answers7

3

There is no way you could do it without using extending an exception class at all. But you can achieve it without an explicit extends ... sort of.

public class Test {
    public void method() {
        throw new RuntimeException() {};
    }
}

The above declares and throws an anonymous subclass of RuntimeException.

Of course this is a pointless thing to do. Since the class is anonymous, you can't name it in a throws clause or handle it by name in an exception handler.

See also: Throw anonymous exceptions in Java


Alternatively, you could extend either Error, a subclass of Error or .... Throwable. But you shouldn't.

  • The Error exceptions are generally assumed to be defined and thrown by the JVM or the standard libraries1. So custom subclasses in the Error hierarchy would be (to say the least) surprising.
  • If you extend Throwable directly, you are liable break code that assumes that Exception and Error are the only subclasses of Throwable.

1 - That's not what the javadoc states ... but people assume it to be the case.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

Leta make a custom ResourceAlreadyExistsException class . It will extends the RuntimeException class, and you can add as many parameters to it as you like. I've kept it concise like this.

public class ResourceAlreadyExistsException extends RuntimeException {

    public ResourceAlreadyExistsException(String property, String value) {
        super(String.format(
            "Resource with property %s and value %s already exists." +
            "Make sure to insert a unique value for %s",
            property, value, property));
    }
}

Whenever I need to check for a unique resource, I can tell the user which specific property has what value that causes the error. Furthermore, I notify the user what action must be taken to avoid the error.

Say, I chose to use error *** for my ResourceAlreadyExistsException. Still, I need to hook up this error message to the ExceptionResponseHandler. The extra method is very similar to the method that we usually create for handling all exceptions. In fact, you can easily copy-paste this method for all the exceptions you have. All you have to do, is changing the Exception class to your exception and change the HttpStatus..

@ExceptionHandler(ResourceAlreadyExistsException.class)
public final ResponseEntity<ExceptionResponse> handleResourceAlreadyExistsException(
    ResourceAlreadyExistsException ex, WebRequest req) {
    ExceptionResponse exceptionResponse = new ExceptionResponse(
        new Date(),
        ex.getMessage(),
        req.getDescription(false)
    );
    return new ResponseEntity<>(exceptionResponse, HttpStatus.UNPROCESSABLE_ENTITY);
TanvirChowdhury
  • 2,498
  • 23
  • 28
1

One could extend the class Throwable.

Jonathan Rosenne
  • 2,159
  • 17
  • 27
1

since OP specifically is asking without using extends(I take it you can't extends classes like Throwable) you can use Exception with the parameter like:

throw new Exception("this is my custom exception");

now whereever you catch this exception you can check the message like

if(e.getMessage().equals("this is my custom exception")){
  //TODO code here
}

now I would fire anyone who would write the code like that but oh well for the sake of interview...

nafas
  • 5,283
  • 3
  • 29
  • 57
0

You can extends Throwable but it is not recommended.

0

Custom Exception in Java is also called as user defined Exception. In this Exception class can be created by user itself. Exception message, Exception generate, Exception handle, all things are created and manage by the user or by the developer. we have to create one exception class just extending its by predefined generalize exception class.

class UserDefineException extends Exception
{
public UserDefineException()
{
super(“Invalid Age Exception”);
}
}
public class TestDemo
{
public static void main(String[] args)
{
if(args.length ==0)
System.out.println(“Age”);
else
{
try
{
int age = Integer.parseInt(args[0]);
if(age<18 || age>60)
{
throw new UserDefineException();
}
else
{
System.out.println(“Group of Party”);
}
}
catch(UserDefineException e)
{
System.out.println(e);
}
}
System.out.println(“Normal Flow”);
}
}

for more information check out this link : https://arzatechs.com/how-to-use-custom-exception-in-java/

Raiyan Shahid
  • 49
  • 1
  • 3
-1

Well you can import an exception instead of extending it. Just import the package and use it in your custom exception.

Raymo111
  • 514
  • 8
  • 24