0

I have been searching online and researching in some books, but the examples given are limited and I still have some doubts in user-defined exception.

Using the following codes as an example:

//Conventional way of writing user-defined exception
class IdException extends Exception  

{
    public IdException(String s)
    {
        super(s);
    }   
}

class Product
{
    String id = new String();
    public Product(String _id) throws IdException
    {
        id = _id;

        //Check format of id
        if (id.length() < 5)
            throw(new IdException(_id));
    }
}

It seems that the conventional way of writing a user-defined exception is almost always the same. In the constructor of the user-defined exception, we always call super(msg). This triggers a question in me: If most exceptions are implemented this way, what difference are there between all these exceptions?

For example, I can have multiple user-defined exceptions, but all seems to do the same thing without any differences. (There is no implementation in these exceptions, what makes them work?)

Example:

class IdException extends Exception
{
    public IdException(String s)
    {
        super(s);
    }   
}

class NameException extends Exception
{
    public NameException(String s)
    {
        super(s);
    }   
}

class ItemException extends Exception
{
    public ItemException(String s)
    {
        super(s);
    }   
}

QUE: So shouldn't we (for example) implement the checking of id inside the exception class? If not all exception classes just seem to do the same thing (or not doing anything).

Example of implementing the check in an Exception:

class IdException extends Exception     {
    public IdException(String s)
    {
        super(s);
        //Can we either place the if-statements here to check format of id ?
    }
    //Or here ? 
}
user3437460
  • 17,253
  • 15
  • 58
  • 106

4 Answers4

2

Ideally you should not implement your business logic inside Exception. Exception tells information about exceptional behaviour, And in Custom Exception you can customise that information.

Find the best practice to write Custom Exception.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • That is the point I do not understand. If we don't implement the logic within the exceptions. In my example, `IdException`, `NameException`, & `ItemException` all seems to does the same thing. So why do we still implement so many exception which does the same stuff? Thanks. – user3437460 Jul 24 '14 at 08:57
  • @user3437460 The type of the exceptions can be reused in code to produce different branches for different types of exceptions in `try { ... } catch (...) { ... }` blocks (see @sp00ms answer) and you can create a formatted Message from key parameters to make `throw` code more readable and still produce a nice and readable message text (see my answer). – AlexR Jul 24 '14 at 09:02
  • Custom Exceptions are reasons for custom causes. In each custom Exception you can customise your information very specifically. – Subhrajyoti Majumder Jul 24 '14 at 09:07
  • @SubhrajyotiMajumder All along I thought exception should have the capabilities to check varaious types of error by themselves. For now, it seems that we have to manually `try`, `catch` these errors and manually categorize them to the right exception? Is this correct? Thanks. – user3437460 Jul 24 '14 at 09:10
  • Yes thats right. That is basic of `try-catch(Exception)-finally(optional)`. – Subhrajyoti Majumder Jul 24 '14 at 09:13
0

We have so many Exceptions already defined in java. All do the same thing : to notify user about the problem in code.

Now suppose we have only one Exception, then How we can what error occurs when the exception is thrown. After all, name matters a lot.

Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
0

To take your example Exceptions, I would create a more elaborate message by formatting the data provided:

public IdException(String id, String detail) {
    super(String.format("The id \"%s\" is invalid: %s", id, detail));
}

throw new IdException(_id, "Id too short.");

This way there is no real logic in the IdException class other than providing the given value (id) and a detail message together in the e.getMessage() String so debugging and logging is easy to read and the code itself is also straightforward:

There is something wrong with the Id _id, namely it is too short. Thus we throw it back at the caller.

Also, when you throw different types of Exceptions in a code, it allows caller code to handle each Exception type differently:

try {
    getItem(id, name);
} catch (IdException ex) {
    fail(ex.getMessage()); // "The Id is bogus, I don't know what you want from me."
} catch (NameException ex) {
    warn(ex.getMessage()); // "The name doesn't match the Id, but here's the Item for that Id anyways"
} catch (ItemException ex) {
    fail("Duh! I reported to the dev, something happened");
    emailToAdmin(ex.getMessage()); // "The Item has some inconsistent data in the DB"
}
AlexR
  • 2,412
  • 16
  • 26
-1
class MyException extends Exception{
       int x;
       MyException(int y) {
         x=y;
       }
       public String toString(){
         return ("Exception Number =  "+x) ;
      }
    }

    public class JavaException{
       public static void main(String args[]){
      try{
           throw new MyException(45);

      }
     catch(MyException e){
        System.out.println(e) ;
     }
    }
}

output: Exception Number = 45
jeff porter
  • 6,560
  • 13
  • 65
  • 123