Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why user defined exception classes are preferred/important in java?

Tags:

java

exception

When we have System defined exception classes in Java, then why there is need to make user defined exception classes? Because my teacher told me to make Exception classes in my project.

Any elaborate example will be good.

like image 206
Mr37037 Avatar asked Oct 15 '25 09:10

Mr37037


2 Answers

User defined exceptions can be much more descriptive.

Example :

public void setName (String name)
    throws NameException
{
    if (name == null || name == "")
        throw new MissingNameException ();
    if (name.length > 30)
        throw new InvalidNameException (name); // this exception can contain a message that explains why the
                                               // name is invalid and what a valid name looks like
    _name = name;
}

The alternative to creating your own exception is to use a predefined exception such as InvalidArgumentException, but that would give less information to the method that catches this exception (since it can be thrown by many methods in many classes).

Defining a class hierarchy of exceptions gives the user of your classes better control when handling the exceptions.

like image 190
Eran Avatar answered Oct 16 '25 21:10

Eran


Because the existing exceptions may not be suitable for your situation. By creating your own exception you can make it easier to understand why the exception is thrown and it will stand out better than if you were using an existing exception.

like image 30
Kayaman Avatar answered Oct 16 '25 21:10

Kayaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!