Closed . This question is opinion-based . It is not currently accepting answers.
From Best Practices for Exception Handling :
Try not to create new custom exceptions if they do not have useful information for client code.
What is wrong with the following code?
public class DuplicateUsernameException extends Exception {}
It is not giving any useful information to the client code, other than an indicative exception name. Do not forget that Java Exception classes are like other classes, wherein you can add methods that you think the client code will invoke to get more information.
We could add useful methods to DuplicateUsernameException
, such as:
public class DuplicateUsernameException
extends Exception {
public DuplicateUsernameException
(String username){....}
public String requestedUsername(){...}
public String[] availableNames(){...}
}
The new version provides two useful methods: requestedUsername()
, which returns the requested name, and availableNames()
, which returns an array of available usernames similar to the one requested. The client could use these methods to inform that the requested username is not available and that other usernames are available. But if you are not going to add extra information, then just throw a standard exception:
throw new IllegalArgumentException("Username already taken");
When should we create a user-defined exception class in Java?, We should create our own exceptions in Java. Keep the following points in mind when writing our own exception classesAll exceptions must be We should create our own exceptions in Java. Keep the following points in mind when writing our own exception classes All exceptions must be a child of Throwable. If we want to write a checked exception that is automatically enforced by the Handle or Declare Rule, we need to extend the Exception class.
from a good design/practice point of view, when should we create and use custom java exception classes instead of the ones already predefined in java?
When the existing exception names don't cover your need.
Another design concern is to extend the "good" exception class; for instance, if you raise an exception related to I/O, you should ideally inherit IOException
; if the exception indicates a programmer error, you should inherit RuntimeException
(ie, make your exception unchecked).
Raising custom exceptions also allows you to treat exceptions in a more precise manner; for instance, if you have defined FooException
inheriting IOException
, then you can have a special treatment for it:
try { ... }
catch (FooException e) { ... } // Catch it _before_ IOException!
catch (IOException e) { ... }
Also, exceptions are classes like any other, so you can add custom methods etc; for instance, Jackson defines JsonProcessingException
which inherits IOException
. If you catch it, you can obtain location information of the parse error using .getLocation()
.
Create a Custom Exception in Java, In this tutorial, we'll cover how to create a custom exception in Java. We'll show how public class IncorrectFileNameException extends Exception { We are consequently losing the root cause of the exception. To fix this, we When should we create our own custom exception classes? The term exception lets the programmer to know that there is something exceptional has occurred in the program. Apart from Java exception class library, a custom exception can be created by the developer. This customization gives the power to deal with application centric exceptions.
certainly when you expect to be able to programmatically handle an exception - ie it's easy to create separate catch statements for different exception types, ie:
try{
buyWidgets();
}
catch(AuthenticationException ex)
{
promptForLogin();
}
catch(InsufficientFundsException ex)
{
promptToRefillAccount();
}
//let other types of exceptions to propagate up the call stack
On whether the above constitutes inappropriate use of exception for flow control
While exceptions are more CPU-expensive than if-else statements (mainly due to cost of constructing a stack trace), cost is relative and should be assessed in the context of particular use case. Not every piece of code needs to be web-scale fast and some people find reading and testing conditionals more cumbersome. For example pretty much all transaction managers implement commit-rollback-retry idioms using exceptions. (Try writing a transaction retry aspect without catching an exception)
Separately, one should adhere to separation of concerns principle: not every piece of code needs to deal with every possible condition. Whether not being logged in while buying widgets is an exceptional case really depends on the app and particular place in the app code base. For example, you could have a Service with operations for logged-in users. It makes no sense for methods in that service to deal with authentication - instead these methods would expect code earlier in the call chain to ensure user is authenticated, and thus simply throw exceptions if that is not so. Thus, for those methods being not logged in IS an exceptional case.
Implement Custom Exceptions in Java: Why, When and How, The Java Exception class describes the kind of event, and the That's the only thing you need to do to create a custom exception class. But as I When faced with choosing the type of exception to throw, you can either use one written by someone else — the Java platform provides a lot of exception classes you can use — or you can write one of your own. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.
How to create custom exceptions in Java, Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always Java has many built-in exception classes, such as NullPointerException and IllegalArgumentException. At times however, you might want to create your own exception class. For example, as opposed to throwing IllegalArgumentException when a 0 is detected as a divisor during a division operation, you might wish to throw a DivideByZeroException.
I often create custom Exceptions if there is more information that I need to convey instead of just an error message.
For example particular error codes or actual vs expected values. these can also have their own getters so you can programically retrieve these fields without having to parse the String message which could break if you ever change the text of the message. (Or translate it into a different language)
If you make your own Exceptions, I would recommend extending the common JDK built in exceptions so your API can say throws IOException
but it really throws MycustomIOException
. that way users of your API don't have to know about your own custom versions unless they want to.
Creating Exception Classes (The Java™ Tutorials > Essential , You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's. Do you need Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones. Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
How to Make Custom Exceptions in Java, Sometimes, we need to create our own for representing business logic in Java, there's no need to define custom exceptions and you should just stick to the ones we initialize the exception's error message and the base class takes care of You should only implement a custom exception if it provides a benefit compared to Java’s standard exceptions. The class name of your exception should end with Exception. If an API method specifies an exception, the exception class becomes part of the API, and you need to document it.
Creating Your Own Exception Classes, Do you need an exception type that isn't represented by those in the Java platform? Would it help your users if they could differentiate your exceptions from those Creating an exception class. To create a custom exception class, you just define a class that extends one of the classes in the Java exception hierarchy. Usually you extend Exception to create a custom checked exception. Suppose that you’re developing a class that retrieves product data from a file or database, and you want methods that encounter I/O errors to throw a custom exception rather than the generic IOException that’s provided in the Java API.
Creating Your Own Exception Classes, When you design a package of Java classes that collaborate to provide some the exceptions that your classes throw as you do thinking about and designing You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else’s. Do you need an exception type that isn’t represented by those in the Java platform? Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
Comments Do not throw just an Exception
! It means you have to catch Exception
, which in turn means you also catch all RuntimeException
s, therefore all NPEs etc! "It is not giving any useful information to the client code, other than an indicative exception name": but that can be useful, if you need to do specific error handling for a duplicate name, such as prompting for a different name. Exceptions shouldn't be used for flow control. refer to this for a good explanation as to why: stackoverflow.com/questions/1546514/… That’s an over-simplification. See my edits above. I think that with a example it would be still more helpful ;) @GhostCat example please... I have to admit: I gave an example. What would it help to show how exactly we use exceptions to carry nls information? I gave examples that outline why exceptions might be enriched conceptually.