Correct Java Exception for a malfomed string - java

I have a method that should only accept strings of a certain format. When the format is invalid, I want to throw an Exception. I'm quite new to Java, so am not sure what the correct type of exception to use here is. I found there is a IllegalFormatException, which based on the name sounds right, though the docs make me rather unsure about this. What is the correct Exception class to use here?
The method in question is the constructor of a PropertyId class, which takes one string argument, which should match '/^p[1-9][0-9]*$/i'. It should behave essentially the same as this equivalent in Python.
I'd prefer using an Exception provided by the standard library, unless there really is none that is appropriate, or it is generally agreed on that in my case a new Exception derivative should be created.

I am with #TwoThe. IllegalArgumentException is the way to go. In fact, I actually don't think there should be much debate. This situation is exactly what IllegalArgumentException was made for.
IllegalFormatException is misleading for sure, but that (and its subclasses) is for a completely different case--when the format string you provide for output is invalid.
Generating your own custom exceptions should only be done with great care. Only when you have a special case where no standard exceptions apply. That isn't true here, and you don't want your clients to have to deal with non-standard stuff unless absolutely necessary.
Remember, with great power comes great responsibility.

This appear reasonable to me, from the Javadoc for IllegalFormatException
Unchecked exception thrown when a format string contains an illegal
syntax or a format specifier that is incompatible with the given
arguments. Only explicit subtypes of this exception which correspond
to specific errors should be instantiated.
As #BasvandenBroek points out, this is appropriate for String which contain format information, rather than checking the format of a String.
However, it may be that it's parent IllegalArgumentException is best. NumberFormatException is close, but not approriate, and it's parent is also IAE.
Note: you can create your own sub-class of IllegalArgumentException
public class StringValidationFailedException extends IllegalArgumentException {
public StringValidationFailedException(String message) {
super(message);
}
}

Try IllegalArgumentException.

There are many exceptions in Java, but it sounds like you may need a custom exception depending on what you mean by format. There are many examples of that on this site. Here are just two links.
How to create a custom exception type in Java?
How to define custom exception class in Java, the easiest way?

Related

When to use "throws RuntimeException" Java [duplicate]

This question already has answers here:
In Java, when should I create a checked exception, and when should it be a runtime exception? [duplicate]
(14 answers)
Closed 4 years ago.
I am doing a code review and I have came across this method definition:
public void something() throws RuntimeException
Is there a rational reason to write 'throws RuntimeException' in Java?
RuntimeException is unchecked exception and therefore can be thrown from any place in the code. Saying "Hey, this method can throw RuntimeException" and knowing that any piece of code can do so may be redundant. The only reason I can think of, you would like to make it explicit is for documentation purposes, eg. "Throws RuntimeException when some specific thing happens", but then it probably belongs to javadoc, not to method signature.
Everything is context-dependent, of which you shared none; but on a general note in may be said that this very rarely makes sense. Methods declare unchecked exceptions for documentation purposes, but these are normally specific exceptions carrying some domain-specific meaning. Declaring to throw a completely generic unchecked exception is thus quite hard to justify, although I cannot say there is absolutely no situation where it may make sense.
Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
This types of exceptions depend directly of code, for example, "ArrayIndexOutOfBoundsException".So, if you don't use arrays, arraylists, casting or something what could throw a RuntimeException, it wouldn't be neccesary to write that.
Any method can throw RuntimeException, like NullPointerException being most common. So if a method throws RuntimeException (or it's subclass), it's usually not put that in method signature.
So according to me, it just shows inmaturity of the programmer as it doesn't add any value. Though, it's not asked but even the method name i.e. something() is fishy. It doesn't convey any meaning to the reader.

Should I declare all exceptions thrown from a method in the method signature or just the super class of the exceptions?

When I throw checked exceptions from a method should I just declare the super class of the exceptions in the method signature or all the different types? If I have the following exceptions:
private class SuperException extends Exception {
}
private class SubExceptionOne extends SuperException {
}
private class SubExceptionTwo extends SuperException {
}
Should the method signature be:
void confirmAccount() throws SubExceptionOne, SubExceptionTwo;
or
void confirmAccount() throws SuperException;
In the last method signature, how do I tell other developers what exceptions that could be thrown from the method? If the different sub types need different handling?
The interface should be as stable as possible. So probably Super. Many libraries use the "Super" strategy, because exception specs cause far more annoyance in maintainability than readability or safety they add. Even the IOException is a Super that nearly all Java library code uses instead of declaring more specific exceptions. (But when they do declare more specific exceptions, it's because the contract is that more general IOExceptions won't be thrown. Read on.)
You might list Sub1 and Sub2 if you really do want to say each of those exceptions can be thrown, but don't want to say that any derivative of Super can be thrown. Perhaps Sub1 is NumberCrunchException and your method calls crunchNumbers() and users of your method can be assured that's the only exception-ful thing your method does. In that case the specific strategy is better.
If the different sub types need different handling, then definitely declare the two different exceptions. Never expect the developer using your method to guess that you are actually throwing different types of exceptions.
If you declare two distinct exceptions, and the user knows from the Javadoc that they are actually descendents of the same class, the user may choose to catch them both with a catch (SuperException e) rather than two individual catch clauses. But it depends on the user's choice.
If you don't declare them separately, your IDE is not going to add the appropriate #Throws to your Javadoc comment. And your Javadoc will therefore only indicate that you're throwing SuperException, which will leave the user in the dark. Solving this by just putting it in the text of the comment is not a real solution. If any tool is using reflection to determine what your method throws, it will not see the individual exceptions in the array returned from Method.getExceptionTypes().
If the functionality expected of the different exceptions is more or less the same and it's just a matter of how they will appear in the logs, it may be better to just use the parent exception, with different messages.
The throws clause is there to convey useful information to the calling method about what might go wrong during invocation of this method. That means that how specific you are will depend on how much information you want to convey; and that will be application-dependent.
For instance, declaring throws Exception is almost always a bad idea: the information this conveys is just "something might go wrong", which is too vague to be useful. But whether calling classes are going to need perfectly fine-grained information in the throws clause is something you need to decide by looking at your program. There's no set answer.

Programmatically distinguish exceptions

The type of an exception is often enough to handle it properly (for example you try to open a file and get a FileNotFoundException). However there are cases where you might catch multiple exception of the same type. For example, an IllegalArgumentException that can be caused by more than one argument. The IllegalArgumentException does not add any additional methods (or public fields) to the Throwable interface (accoding to the online javadoc) which means that the only information that you can rely on are the nested exception (which may or may not exist) and the message (which is for human consumption).
I don't like the idea of extending IllegalArgumentException to add structured information to it, because other people would have to learn the new class. And I don't like the idea of littering projects with very specific exception classes.
Using the message field is also a bad idea because it's not meant for programmatic access.
I think IllegalArgumentException should have included details such as the class function and argument(s) in question. And in general custom exceptions should provide additional detail (other then just their type) for a more fine grained exception handling.
What are considered generally the best practices for designing exception classes, and handling exceptions of the same type?
As a general rule, I think it is ideal to have one class of exception per "type of action a caller might reasonably want to take". Of course, for one's own custom exceptions there could be a boolean or enum field providing some extra disambiguation, rather than creating trivial subclasses.
In your specific case I'm not convinced that trying to handle the exception is a good idea. RuntimeException and its subclasses usually represent coding issues, and the same is true of IllegalArgumentException. If the argument is illegal it shouldn't be passed in in the first place.
If you're in a situation where you're not sure if an argument is valid (maybe it's user input, or maybe you don't know the specific object you're calling the method on) then a better approach would be to have some way of checking the validity of the argument before passing it. Rather than say "do this" and catch the exception, ask "can I do this?" before calling.
Exception classes should be designed so as to provide all that is needed when they are caught. Note that try/catch statements are actually a form of type switch, so in general it is cleaner to create additional exception classes rather than confuse program logic by nesting too many if's within catch clauses.
It has to be said that catch clauses are not very convenient if you want to organize your error handling code in an object oriented fashion, so there are different trade offs to keep in mind.
Note that standard exception classes do have information available on what piece of code caused the exception, even though I would not advise you to base on it your error handling logic.
If the current exception was thrown in a catch clause for a different exception this should be available with the getCause() method, while the getStackTrace() should provide access to the stack of calls that were active when your exception was thrown.
Again I don't advise you to use this information except for debugging purposes.
Its true that the predefined exception classes are very general. But if you want more specific details about the exceptions then you should go for user defined exceptions. you should create your own exception classes with any level of details!
here is the pseudo code:
public class TooManyArguments extends exception{
public String toString(){
return ("..whatever information you want to give for this exception..")'
}
}
and whenever you encounter exceptional situation throw an instance of this class
throw new TooManyArguments();

How to organize Exception classes without code duplication?

I have a number of custom Exception-inheriting classes in my package, which do not differ from their base class. The only purpose I have them is to distinguish one exception cause from the other, when it is thrown. This is how one of my Exception class looks like:
package com.XXX;
/**
* Thrown when query format is invalid.
*/
public class InvalidFormatException extends Exception {
/**
* Public ctor.
* #param m Supplementary message
*/
public InvalidFormatException(final String m) {
super(m);
}
}
The problem is that all classes are absolutely identical, like twins. The only thing which is different is their names. I don't like this situation, since it's an obvious code duplication. In other languages (like PHP, Python, etc.) I would declare these classes on-fly during runtime, but Java doesn't allow this, as well as I understand. Is there any workaround?
You may create a generic class with a code property settable with the controller. This way you can have only one class and instance when thrown.
That said, I don't agree when you say classes are twins. They represent totally different functional exception. Based on the separation of concerns pattern, the current implementation is the correct one. Using my generic class will mix concerns in your class and that should be forbidden.
Moreover, I see you inherit from Exception... I will not explains a lot but you should use RuntimeException for functional exceptions in your application. Look around on the web, there is a lot of literature about it.
The simple answer is "no", you cannot easily declare on the fly classes with Java. That noted, if you really wanted to do this, it is possible, you'll need to study how Java can compile classes at runtime. Another simplification is if all your exception classes are the same, excepting their names, you could define a base Exception class of your own that they extend.
Another thought, what value are you getting from having all these different Exception classes? Are you clients going to handle things differently depending on what Exception's thrown? If not, I'd suggest examining the Exception hierarchy you've created and simplifying.
Then, if you go that far, consider using RuntimeException as well. This might be grounds for a holy war, but if you really don't do anything special with what's thrown, there's not much value in forcing you client to deal with it. See Bruce Eckel's article on the subject for some perspective.

Checked equivalent to IllegalArgumentException?

I have a method that takes an enum as a parameter and returns some information dependent on that parameter. However, that enum contains some values which should not be handled, and should raise an error condition. Currently the method throws an IllegalArgumentException but I would like this to be a checked exception to force callers to catch it (and return gracefully, logging an error). Is there something suitable or should I create my own Exception subclass?
I'm open to other patterns as well. A reasonable reaction would be that all values of the enum should be handled, but that isn't the case. When a new value is added to the enum, I want to make sure that this method does the right thing - alerting a human is preferable to using some default return value in this case.
Thanks for any advice.
You can certainly create a checked exception of your own (such as UnhandledEnumType), or you could catch and handle the IllegalArgumentException. It sounds a little fishy that only some values of the enum should be handled. One of the purposes of an enum is to bind values to a certain set of values, and I would expect all to be handled. If you're worried about new ones being added, you should have a test that tests that all values are properly handled (by using the values() method of the enum to ensure they are all tested).
The questions are:
how "normal" are cases when the method is called with an unsuitable enum parameter?
can you handle these cases gracefully and then continue processing?
From what you describe, it is not "normal" (happens only when a new enum value is added and the method is not updated properly - i.e. when a bug was introduced). So to me this sounds more like a case for RuntimeException (i.e. unchecked). Callers of this method can still catch an unchecked exception if they really want to, but they are not forced to.
OTOH I would try to eliminate the case you describe, by moving the data your method is returning right inside the enum. This way whenever a new enum value is added, there is no way the relevant data could be forgotten.
If you are interested, you may want to check out this tutorial.
How about InstantiationException?
Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to:
the class object represents an abstract class, an interface, an array class, a primitive type, or void
the class has no nullary constructor

Categories

Resources