Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the advantages to define custom exception?

Any big reasons to define custome exceptions in Java?

like image 646
user496949 Avatar asked Mar 09 '11 11:03

user496949


People also ask

What is the benefit of a custom exception?

Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard Java exception. These can store additional information, like an application-specific error code, or provide utility methods that can be used to handle or present the exception to a user.

What are some advantages of exceptions?

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.

Why would I use a custom exception class?

The purpose of a custom exception class is to integrate the look-up of localized message strings in a custom message catalog into the mechanism that is used for error reporting in the client infrastructure.

What is custom defined exception?

In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.


1 Answers

Two reasons immediately spring to mind:

  1. Simply so you don't say try { ... } catch (Exception e) { ... } - having your own subclasses lets you treat distinct exception cases separately. (Such as the difference between not having permissions to run a report, and the report execution failing).
  2. You can add extra context - so for example if you have your own AlreadyLoggedInException, say, that exception can have a method to retrieve the IP address from which the other session was started. Or an AccountLimitExceededException could contain the current account limit. Extra information in the exception allows you to potentially take a more well-informed response when catching it.
like image 109
Andrzej Doyle Avatar answered Sep 18 '22 16:09

Andrzej Doyle