i Have the following code but i am confused how i throw the InvalidLockCombinationException. This
exception (which should not have any methods) will indicate that an attempt to assign a
combination to a lock failed (thus making the combination invalid for that lock). If the combination is invalid
(if not all its numbers are in the dial) then the constructor should throw a new
InvalidLockCombinationException. By throwing this exception we can avoid creating locks with
invalid combinations (which in real life will be defective). All locks are open when created this is what i have so far. Any help would be appreciated on how to get the exception working.
public class Lock{
public Combination correct;
public int upperLimit;
public boolean isOpen;
public Lock(int aLimit, Combination aCombo) throws InvalidLockCombinationException(){
correct = aCombo;
upperLimit = aLimit;
isOpen=true;
int[] comboHolder = new int[3];
comboHolder = aCombo.getNumbers();
for(int i=0; i<comboHolder.length;i++){
if(comboHolder[i]<0 || comboHolder[i]>upperLimit){
throw InvalidLockCombinationException;
}
}
}
}
An exception is an object too. You can't really throw the idea of a ball, you need an actual ball to throw.
throw new InvalidLockCombinationException();
Nullary constructor given since you said it should be a basic exception sans extra fields or methods. I would still try to accept a String message for extra info but that's beyond the scope of this answer.
I recommend using an actual IDE. It would politely tell you about what's happening with its red mark.
Related
The value in the setter comes from a JTextFeild. I have try different method but it isn't working. I want to print out my custom error message. It isn't working for double, the String variable print the error message in the stacktrace.
This is the String method.
public void setInventoryname(String inventoryname) throws Exception {
if(inventoryname.isEmpty()){
throw new Exception ("Medicine name cannot be empty");
}
else{
this.inventoryname = inventoryname;
}
}
result of the string method.
java.lang.Exception: Medicine name cannot be empty
This is the double method
public void setInventorydesc(double inventorydesc) throws Exception {
if(!Double.toString(inventorydesc).isEmpty()){
throw new Exception("Set a number in Inventory qunatity");
}
else
{
this.inventoryqty = inventorydesc;
}
}
The result of double
java.lang.NumberFormatException: For input string: "dfasdf"
I want to receive the same result as of string for double.
Use Validator api and put your message.
Check org.apache.commons.validator
Double variable can never be empty, it can be zero.
You'll have to initialize the double variable, otherwise compiler will throw error.
If the zero value is what you mean by empty then you can compare that with zero to check.
You can not keep double variable uninitialized, it's all right with string but not with double.
Maybe you should step back and ask yourself for a second: does that really make sense?
What I mean is: you have two different methods, that take completely different arguments; and that have completely semantics; and still you are asking that both give you the same error message?
Lets have a closer look. First of all, throwing Exception objects is really bad practice. If you want to use a checked exception, then you better create your own subclass and use that. If you prefer unchecked exceptions, then you could throw IllegalArgumentException.
And just for the record: when you receive a double argument, that thing is always a number. Somebody already took the incoming string and made it a number. So your method is absolutely pointless. In other words: besides the things I told you, you should have a look into the code calling your methods.
Finally: read java language style guides. You should use camelCase for your variable and method names. And there is absolutely no need to abbreviate, call the thing inventoryQuantity; then everybody knows what it is! And you know, it is absolutely wrong that a method called setInventoryDesc changes the value of a field called inventoryQuantity. This might sound like nitpicking, but be assured: being precise and disciplined is one of the core practices in programming!
Pass inventorydesc as a string first - and then work with it ...
public void setInventorydesc(String inventorydesc) throws Exception {
if(inventorydesc==null ||inventorydesc.isEmpty()){
throw new Exception("Set a number in Inventory qunatity");
}
else
{
try{
this.inventoryqty = Double.parseDouble(inventorydesc);
}catch (NumberFormatException e){
throw new Exception("Inventory qunatity must be double");
}
}
}
If the number comes from a text field first you must parse it to get the double.
public static void setInventorydesc(String inventorydesc) throws Exception {
try{
double convertedInventorydesc = Double.parseDouble(inventorydesc);
this.inventoryqty = convertedInventorydesc;
}
catch (NumberFormatException ex){
throw new Exception("Set a number in Inventory quantity",ex);
}
}
try using this method
Double.isNan(double d)
Use this method to verify if the value is numeric or not.Or try to type cast the the string to double if it goes into catch block then display error message to user
Let's say I have a class like the following one:
public class Parameter {
private double[] parameterValues;
public Parameter(double[] parameterValues) throws BadElementInitializationException {
checkParameterValues(parameterValues);
this.parameterValues = parameterValues;
}
public double[] getParameterValues() {
return parameterValues;
}
public void setParameterValues(double[] parameterValues) throws BadElementInitializationException {
checkParameterValues(parameterValues);
this.parameterValues = parameterValues;
}
private void checkParameterValues(double[] parameterValues) throws BadElementInitializationException {
if(parameterValues == null)
throw new BadElementInitializationException("Parameter values cannot be null");
if(parameterValues.length == 0)
throw new BadElementInitializationException("Parameter values cannot be empty");
}
public int noOfValues(){
return parameterValues.length;
}
}
And the array is later used to perform some calculations.
My question is, where should I check that parameterValues is not null, nor empty? Should I do that in the Parameter class, like I did, or should I do that in the class which performs calculations?
Moreover, should I throw an exception here, or in the Calculation class? And what would be the reason to throw checked and what to throw unchecked exception? My goal is to make a stable application that won't crash easily.
You should do it in all places where getting an null or empty array is not valid. If you do it just in your Parameter class and rely on this having done the check in your Calculator class, then what if you start to use your Calculator class somewhere else? Who are you going to rely on to do the checks there? If you do it in the Calculator class and then refactor the Parameters class to use something else in the future, then your check will go away.
If its also invalid to have a null or empty array in your Calculator class then you need to check there as well.
Alternatively pass an object to both which cannot be empty and then you only need to make the null check.
Should I do that in the Parameter class, like I did, or should I do
that in the class which performs calculations?
In my opinion, better to check in Parameter class then any other classes. You could see how it do in google guava , for example, in most class they use:
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
or
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
...
Moreover, should I throw an exception here, or in the Calculation
class?
If you check your parameters in Parameter class, better throw in Parameter class also. In addition to, you may use some standart function to check and throw exception, for example from google guava:
com.google.common.base.Preconditions.checkNotNull
com.google.common.base.Preconditions.checkArgument
com.google.common.math.MathPreconditions.checkPositive
And what would be the reason to throw checked and what to throw
unchecked exception?
A checked exception is good if you think that you must catch and working this exception later. In most case, for wrong parameters quite enough unchecked exception, like standart IllegalArgumentException in Java. Also, a checked exception need to say other programmers (who use this API) that this exception could be happened, and they need to working with it. Working with an unchecked exception is quite easy for programmer (and often reduce your source code), however a checked exception become your code is more reliable.
A more info about checked and uncheked exceptions, you could find in this post
Suppose we have a class Graph and another class called GraphWrapper.
Graph class has a method called returnAdjVertices.
public List returnAdjVertices(int vertex) {
if (vertex < 0 || vertex >= maxVertexCount) {
throw exception
}
}
Now we have a wrapper function in GraphWrapper which would calculate degree of a vertex
public static int getDegree(Graph graph, int vertex) {
if (graph == null) throw new NullPointerException();
if (vertext < 0 || vertex >= graph.maxVertexCount) throw exception // REDUNDANT
return graph.returnAdjVertices(vertex).size();
}
Now a call to find degree is checking for vertex bound condition twice.
This means we are doing a redundant check. What is the best practice recommended for exception handling in such a case ?
You can either rethrow an exception (it will be done automatically if you don't catch it in your wrapper)
public static int getDegree(Graph graph, int vertex) throws VertexOutOfBoundsException {
return graph.returnAdjVertices(vertex).size();
}
or catch it in your wrapper and retranslate to another
public static int getDegree(Graph graph, int vertex) throws WrapperException {
int result;
try {
result = graph.returnAdjVertices(vertex).size();
} catch (VertexOutOfBoundsException e) {
throw new WrapperException();
}
return result;
}
or even catch it and try to fix it
public static int getDegree(Graph graph, int vertex) {
int result;
try {
result = graph.returnAdjVertices(vertex).size();
} catch (VertexOutOfBoundsException e) {
result = fixGraphAndReturnAdjVertices(graph, vertex);
}
return result;
}
You shouldn't do your check again, because it can be really hard to maintain.
Selection of variant is always situative.
First variant (automatic rethrow) is good when your wrapper is on the same abstraction level with wrapped object.
Second variant is good when wrapper and wrapped objects are on different abstraction levels, as an example I can propose that "FileNotFoundException" of an object working with HDD can be translated to something like "CannotLoadDataException" of an object that try to load something if it makes no sence for caller what exactly goes wrong.
Third variant is good when your wrapper can fix things :)
So it's all up to you. Hope my answer helps.
As you note, the check is redundant. So you can simply drop it from the wrapper. The exception will move up the stack of calls.
I would make it clear in the documentation of both methods that an exception is thrown when the vertex is not between the accepted bounds. Or at least make it clear in the documentation of the wrapper method that it calls the wrapped method internally, and thus throws the same exceptions.
In this particular case? It's redundant, and should be eliminated–at least if you'd be throwing the same exception, and there are no other possible side-effects in the code.
In the general case? It depends entirely on your needs, the code, etc.
One issue is that if your explicit intent is to perform the exact same check you'd need to monitor the wrapped class to ensure the guard clause hasn't changed, or extract the guard logic into a separate method that can be called independently. This is leaky encapsulation, though.
Also, I'd throw an IllegalArgumentException with a message instead of an NPE.
I'm running into this situation where I need to parse a String into an int and I don't know what to do with the NumberFormatException. The compiler doesn't complain when I don't catch it, but I just want to make sure that I'm handling this situation properly.
private int getCurrentPieceAsInt() {
int i = 0;
try {
i = Integer.parseInt(this.getCurrentPiece());
} catch (NumberFormatException e) {
i = 0;
}
return i;
}
I want to just simplify my code like this. The compiler doesn't have a problem with it, but the thread dies on the NumberFormatException.
private int getCurrentPieceAsInt() {
int i = 0;
i = Integer.parseInt(this.getCurrentPiece());
return i;
}
Google CodePro wants me to log the exception in some way, and I agree that this is best practice.
private int getCurrentPieceAsInt() {
int i = 0;
try {
i = Integer.parseInt(this.getCurrentPiece());
} catch (NumberFormatException e) {
i = 0;
e.printStackTrace();
}
return i;
}
I want this method to return 0 when the current piece is not a number or cannot be parsed. When I don't catch the NumberFormatException explicitly, does it not assign the variable i? Or is there some default value that Integer.parseInt() returns?
General style says that if I catch an exception, I should log it somewhere. I don't want to log it. It's normal operation for this exception to be thrown sometimes, which also doesn't sit well with me. I cannot find a function, however, which will tell me if Integer.parseInt() will throw an exception. So my only course of action seems to be to just call it and catch the exception.
The javadoc for parseInt doesn't help much.
Here are the specific questions I'd like to know:
Is there a method that I can call that will tell me if Integer.parseInt() will throw a NumberFormatException before calling it? Then I would have no problem logging this, since it should never happen.
If I simply do not catch the exception, will the valiable not get assigned? Then I will simply initialize it to the value that I want when it's not a number and not catch the exception.
Is there a way to mark the exception somehow explicitly that I don't care about it? I'm thinking this would be something similar to AWTEvent.consume(). If so, then I will do this so that Google CodePro doesn't see this as "unlogged".
Is there a method that I can call that will tell me if Integer.parseInt() will throw a NumberFormatException before calling it? Then I would have no problem logging this, since it should never happen.
Sadly, no. At least not in the core Java API. It's easy to write one, however - just modify the code below.
If I simply do not catch the exception, will the valiable not get assigned? Then I will simply initialize it to the value that I want when it's not a number and not catch the exception.
If you do not catch the exception then the stack will unwind until it hits a catch block that will handle it, or it will unwind completely and halt the thread. The variable will, in fact, not be assigned but this is not exactly what you want.
Is there a way to mark the exception somehow explicitly that I don't care about it? I'm thinking this would be something similar to AWTEvent.consume(). If so, then I will do this so that Google CodePro doesn't see this as "unlogged".
There may be a way to tell CodePro to ignore this particular warning. Certainly with tools like FindBugs and Checkstyle you can turn off warnings in specific locations. (EDIT: #Andy has pointed out how to do this.)
I suspect what you want is something like the Commons lang package mentioned by #daveb. It's pretty easy to write such a function:
int parseWithDefault(String s, int def) {
try {
return Integer.parseInt(s);
}
catch (NumberFormatException e) {
// It's OK to ignore "e" here because returning a default value is the documented behaviour on invalid input.
return def;
}
}
There is NumberUtils.toInt(String, int) in commons lang which will do exactly what you want.
NumberUtils.toInt("123", 42) ==> 123
NumberUtils.toInt("abc", 42) ==> 42
* Is there a way to mark the exception somehow explicitly that I don't care about it? I'm thinking this would be something similar to AWTEvent.consume(). If so, then I will do this so that Google CodePro doesn't see this as "unlogged".
Yes, you can locally disable a CodePro audit rule for one line of code:
http://code.google.com/javadevtools/codepro/doc/features/audit/locally_disabling_audit_rules.html
That said, it is not necessarily required to include diagnostic logging in every exception catch block. Sometimes, the best action is to take a default course. Sometime it's to interact with the user. It depends.
Create your own convenience method for now and future use:
public static int parseInt(final /*#Nullable*/ String s, final int valueIfInvalid) {
try {
if (s == null) {
return valueIfInvalid;
} else {
return Integer.parseInt(s);
}
} catch (final NumberFormatException ex) {
return valueIfInvalid;
}
}
Is there a method that I can call that will tell me if Integer.parseInt() will throw a NumberFormatException before calling it? Then I would have no problem logging this, since it should never happen.
Not that I'm aware of. Keep in mind that if there were, you likely end up parsing the value twice (once to validate and once to parse it). I understand you want to avoid the exception, but in this case, this is catching the exception is the standard idiom in Java and it doesn't provide another (at least that I know of).
If I simply do not catch the exception, will the valiable not get assigned? Then I will simply initialize it to the value that I want when it's not a number and not catch the exception.
You must catch the exception (even if it does nothing) or it will escape the block and throw up through the stack.
Is there a way to mark the exception somehow explicitly that I don't care about it? I'm thinking this would be something similar to AWTEvent.consume(). If so, then I will do this so that Google CodePro doesn't see this as "unlogged".
I don't know of any. I would use the above convenience method (I have something similar in a small collection of general utilities I have available for use on my all projects).
I wouldn't log it if its truly a normal condition that you are handling. I'm not familiiar with Google CodePro, but I would hope there is a way to suppress the warning, e.g. some sort of #SuppressWarnings("xxx") annotation/keyword.
Edit: I wanted to point out these comments in the comments below
This approach still doesn't handle the exception. It's bad form to catch an exception and do nothing with it. This is why I am looking for a better solution
.
... The exception (the situation) is being handled by returning the indicated valueIfInvalid. The "bad form" you are referring to the poor practice of blindly and unthinkingly writing empty catch blocks and never going back to truly consider and address the case. If the exception situation is considered and does the right thing for the situation (even if the right thing is to do nothing), then you've "handled" the exception.
You should catch the Exception as you are doing. It is annoying, but the best approach.
There is no Java API method that will return 0 when the string is not a valid int.
When the string is not an int, an exception will be thrown so your int variable will not be set unless you catch the exception as you are doing.
If its not clear how you should handle it from the getter, you shouldn't catch it and let the caller deal with it instead. If you know how it should be handled you should just do that. Logging it may not be required or very useful in this case.
Logging an exception is more useful if you don't know how to handle the exception and you are leaving it to the person reading the logs.
Your first code block is correct. i won't be implicitly converted to 0 when an exception occurs and you have to catch that exception. Setting i to 0 inside catch is correct; although you can simply replace i = 0; with return 0;. You cannot avoid exception handling in this case.
To clarify, you can use this:
private int getCurrentPieceAsInt() {
int i = 0;
try {
i = Integer.parseInt(this.getCurrentPiece());
} catch (NumberFormatException e) {
// log that an exception occured if it's needed
return 0;
}
return i;
}
As others have mentioned, there is not a built-in core Java API method you can call to validate an integer, but you can use the Character class to validate your input without using exception handling. For example:
package com.example.parseint;
public class ValidateIntExample {
public static boolean isInteger(String s) {
if (s == null) {
return false;
}
s = s.trim();
if (s.length() == 0) {
return false;
}
int start = 0;
if (s.charAt(0) == '-') { // handle negative numbers
if (s.length() == 1) {
return false;
}
else {
start = 1;
}
}
for (int i = start; i < s.length(); i++) {
if (! Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
}
In fact, parseInt itself uses Character.isDigit internally, which you can verify in the JRE source code. (Sorry, I would have included the parseInt method here, but I'm not sure if I'm allowed under the license terms.) If you're using Eclipse and you have the JRE source code attached to your project, you can right-click on the method Integer.parseInt in your code and click Open Declaration.
Lets say have this immutable record type:
public class Record
{
public Record(int x, int y) {
Validator.ValidateX(x);
Validator.ValidateY(y);
X=x;
Y=y;
}
public final int X;
public final int Y;
public static class Validator {
public void ValidateX(int x) { if(x < 0) { throw new UnCheckedException; } }
public void ValidateY(int y) { if(y < 0) { throw new UnCheckedException; } }
}
}
Notice it throws an unchecked exception. The reason is because this is a object that is used quite often and it is inconvenient to have to deal with a checked exception.
However, if this object is in a class library where it may be used to validate user inputs (or some other external input). Now it's starting to sound like it should be a CHECKED exception, because the inputs are no longer up the to programmer.
Thoughts everyone? should i make checked or unchecked, or are there better design for this?
UPDATE:
my confusion is coming from this scenerio: normally Record would be used like this:
Record r = new Record(1,2);
OtherObj o = new OtherObj(r);
there it's up to the programmer, so unchecked exception is ok.
However when you get parameters for Record from a user you want to validate them right? so you might call
Record.ValidateX(inputX);
Record.ValidateY(inputY);
There it might throw a checked exception because inputs are no longer controlled?
Sorry, I normally wouldn't be too concerned with this (personally I think unchecked is fine). but this is actually a problem in a homework and I want to get it right lol.
UPDATE(2):
I starting to think what I need is for ValidateX to throw a checked exception because it is typically what would be used if user input is involved. In that case we could ask the user for input again. However, for the Record constructor, it will throw checked exception because constructing a Record with invalid arguements is an API violation. The new code would look like this:
public class Record
{
public Record(int x, int y) {
try
{
Validator.ValidateX(x);
Validator.ValidateY(y);
}catch(CheckedException xcpt) { throw new UnCheckedException(xcpt.getMessage()); }
X=x;
Y=y;
}
public final int X;
public final int Y;
public static class Validator {
public void ValidateX(int x) throws CheckedException { if(x < 0) { throw new CheckedException; } }
public void ValidateY(int y) throws CheckedException { if(y < 0) { throw new CheckedException; } }
}
}
Now the programmer can validate the parameters before passing them to the Record class. If the does not then it's a API violation and an unchecked exception is thrown.
How does this sound?!
Notice it throws an unchecked
exception. The reason is because this
is a object that is used quite often
and it is inconvenient to have to deal
with a checked exception.
No, I think the reason you throw an unchecked exception here is because it involves a violation of contract on the part of the user of that API, and not an exceptional condition during the normal functioning of that method. See the Java SDK's use of NullPointerException, IllegalArgumentException, etc., which are RuntimeExceptions because they represent a violation of contract.
Bloch, item 58: Use checked exceptions
for recoverable conditions and runtime
exceptions for programming errors.
If the user of your class is able to avoid the problem by using the API correctly (including not passing in values that are documented to be invalid) then it's a programming error, so throw an InvalidArgumentException.
You should never validate user input with an unchecked exception. Exceptions are normally checked because that way you can not forget to handle the exceptions.
Validating parameters used in an api is a completely different kind. These should be unchecked, because otherwise you'll end up adding try/catch to every function call. Whenever a method is passed an invalid argument, this is surely a programming error. The normal way is to throw an IllegalArgumentException or NullPointerException (or any other that suits your needs).
In api calls leave the checked excpetions for
Validations you promise to the caller of the api
Expected exceptional conditions (requested file doesn't exist, write failed etc)
Besides the above, recoverability is also important for deciding for a checked or unchecked exception. If you can never recover (which is normally the case in a programming error) you can (or should?) take the unchecked exception.
Preferably don't write code that doesn't meet the above guidelines. For you that would mean that you have to write a function that returns a boolean or checked exception when using to validate user input, and an unchecked exception when validating input parameters to your functions. Of course your can and should use the same function to validate the exceptions, just wrap the one that returns a boolean or checked exception:
public boolean validateX(int x)
{
return x > 0;
}
private void validateParameter(int x)
{
if (validateX(x))
{
throw new IllegalArgumentException("X is invalid");
}
}
This is a bit more work, but it will give you the best of both worlds. By making the validate parameter function private you can ensure you don't accidentally use it outside of your class. Of course you can also put the if(validateX(x)) ... part inside your constructor.
Really, it's all about expectations. If you expect that under normal program flow an invalid input may be entered, it should be a checked exception so you can recover gracefully. Unchecked exceptions are for error cases that the programmer can't do anything about and doesn't expect to happen normally.
If this is really meant to be for a validator class, then I would expect it to be unusually flexible on its range of allowable input, simply because it's purpose for existence is to test validity, which it can't do nicely by throwing exceptions.
public interface Validator<T> {
public boolean isValid(T object);
}
public final class PositiveIntegerValidator implements Validator<Integer> {
public boolean isValid(Integer object) {
return object != null && object > 0;
}
}
As a rule of thumb I always handle exceptions at the public interface to my component/layer/api. This allows exceptions to bubble up and be handled at the top level - Last Responsible Moment, whilst ensuring I handle the exception in my code, avoiding leaky exceptions.
BTW Some excellent advice regarding database exceptions on this question and general exception handling on this question