我想在某些条件下验证输入集。在这里,我NumberFormatException
在传递号码时得到了。InvalidInputException
如果在文本框中输入的数字包含除数字以外的任何内容,我想抛出。现在,如果我只输入数字,那么我也会得到NumberFormatException
. 这是示例代码。调用validateInput
如下
try {
if (true == validateInput(name.getText().toString(), number
.getText().toString())) {
// do something
}
} catch (InvalidInputException iie) {
Log.d("@gaurav", "not a valid input" + iie);
Toast.makeText(this, "Invalid input set", Toast.LENGTH_LONG)
.show();
} catch (Exception ex) {
Toast.makeText(this, "Problem while cerating contact", Toast.LENGTH_LONG)
.show();
Log.d("@gaurav", "Problem while cerating contact", ex);
} finally {
// do something
}
ValidateInput()
如下:
* Name is valid if it starts with an alphabet otherwise not valid Number is
* valid if the entered text is integer only,
* if not valid number/name throws InvalidInputException, otherwise true
* */
private boolean validateInput(String name, String number)
throws InvalidInputException {
InvalidInputException iie = new InvalidInputException();
try {
if (name.isEmpty() || number.isEmpty()) {
Log.d("@gaurav.exception", "input field empty");
iie.addDescription("Input field is empty");
throw iie;
} else {
if (false == Character.isLetter(name.charAt(0))) {
Log.d("@gaurav.exception", "first letter of name is not a letter");
iie.addDescription("first letter of the name is not character");
throw iie;
}
Log.d("@gaurav.exception", "checking number");
Log.d("@gaurav.exception","number is :"+number+":");
Double.parseDouble(number);
}
} catch (NumberFormatException e) {
Log.d("@gaurav.exception", "In numberFormatexception, adding description, re-throwing iie");
iie.addDescription("Number field should contain integer only");
throw iie;
}
catch (Exception e) {
Log.d("@gaurav.exception", "Exception, re-throwing iie");
throw iie;
}
iie = null;
return true;
}
MyCustomException
如下_
package com.gaurav.contactmanager.model;
public class InvalidInputException extends Exception {
/**
*
*/
private static final long serialVersionUID = 5585822470459144546L;
String description;
public InvalidInputException() {
super();
}
public InvalidInputException(String desc) {
this.description = desc;
}
public void addDescription(String desc) {
description = desc;
}
@Override
public String toString() {
return description + "\n\n" + super.toString();
}
}
Logcat 显示如下内容:
01-02 02:11:59.310: D/@gaurav.exception(408): checking number
01-02 02:11:59.321: D/@gaurav.exception(408): number is :6666:
01-02 02:11:59.330: D/@gaurav.exception(408): In numberFormatexception, adding description, re-throwing iie
01-02 02:11:59.330: D/@gaurav(408): not a valid inputNumber field should contain integer only
01-02 02:11:59.330: D/@gaurav(408): com.gaurav.contactmanager.model.InvalidInputException