I'm preparing for an exam in basic programming. I'm working on exceptions now but can't seem to figure out how to best use it. I give you the first code and then the second where I try to make a checked exceptions. Any input on this would make me grateful!
without the exceptions:
public boolean uttak(int species, int kroner, int skilling) {
if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
{
this.species -=species;
this.kroner -=kroner;
this.skilling -=skilling;
return true;
}
else return false;
with my messy exceptions :
public void uttak(int species, int kroner, int skilling){
try{
if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
{
this.species -=species;
this.kroner -=kroner;
this.skilling -=skilling;
}
}
catch (Exception e){
System.err.println ("Withdrawals can not be done when there is" +
" insufficient money in the machine.");
}
You probably are looking for something like this:
// custom checked exception type
public class WithdrawalException extends Exception {
public WithdrawalException(String msg) {
super(msg);
}
}
public boolean uttak(int species, int kroner, int skilling) throws WithdrawalException { // checked exceptions need to be declared in the throws clause
if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
{
this.species -=species;
this.kroner -=kroner;
this.skilling -=skilling;
return true;
}
else
// throw an exception
throw new WithdrawalException("Withdrawals can not be done when there is insufficient money in the machine.");
}
And use it in the calling code like this
try {
uttak(i1, i2, i3);
} catch (WithdrawalException ex) {
System.err.println("Something went wrong. Message: "+ex.getMessage());
}
Neither of them is correct to me (if that's a topic about exceptions).
It is a good way to throw an unchecked exception when one of the method parameters doesn't satisfy logic of its method:
if (species > this.species || kroner > this.kroner || skilling > this.skilling) {
throw new IllegalArgumentException("message");
}
If you are encountered with a logical issue during the method execution, you should normally throw a checked exception (your own subclass of the Exception, or any other specific checked exception):
if (species > this.species || kroner > this.kroner || skilling > this.skilling) {
throw new MyCustomCheckedException("message");
}
There is no reason to handle an exception on this level (assuming that it is thrown somewhere in the try block, though it isn't in your case).
Related
So I recently asked the question of how to handle Dropbox API Exceptions here. I learned that I would have to parse the DBXEception into its subclasses which there are many of. Now Thinking about this I am wondering what would be the best way to go about handling this.
Currently I plan on using instanceof and checking like this if I want the program to try again it will return true and the program will try again maybe with a exponential backoff with server request
public boolean parseDBX(DbxException e)
{
if(e instanceof AccessErrorException) {//handle Error
}else if (e instanceof DbxApiException) {//handle Error
}etc
}
It would be called in a catch block like this
for(int i =0;;i++) {
try {
ListFolderResult result = client.files().listFolder("/Saves/"+prefName);
while (true) {
for (Metadata metadata : result.getEntries()) {
System.out.println(metadata.getPathLower());
//metadata.
}
if (!result.getHasMore()) {
break;
}
result = client.files().listFolderContinue(result.getCursor());
}
} catch (ListFolderErrorException e) {
createDefFolder();
} catch (DbxException e) {
if(codeHandler.parse(e)&&i<10) {
continue;
}else {
log.write("Error 5332490: a problem was encountered while trying to check for the root file"+e.getMessage());
throw new IOException();
}
}
}
So My Question is there a way to use a switch statement instead(From what I have found the answer is no), and if not, is there a better way to handle checking for the type of exception.
The best approach is to avoid "parsing" the exception at all by catching exceptions of the appropriate type:
try {
...
} catch (AccessErrorException aee) {
...
} catch (DbxApiException dae) {
...
}
In cases when this is not desirable you could associate your own integer ID with each exception type, put it in a Map, and use it in your parse method to distinguish among subtypes in a switch:
static Map<Class,Integer> parseId = new HashMap<>();
static {
parseId.put(AccessErrorException.class, 1);
parseId.put(DbxApiException.class, 2);
...
}
...
public void parseDBX(DbxException e) {
Integer id = parseId.get(e.getClass());
if (id != null) {
switch (id.intValue()) {
...
}
}
}
So I'm trying to validate some TextFields in javaFX and in my earlier programs this have worked, but I doesn't seem to work now, and I can't figure it out! Several hours have been wasted!
Here is a outcast from my programming
This is ONE class to simplify
public class ValidateHelp {
private Text actiontarget = new Text();
public void validateName(TextField firstname, TextField lastname) throws Exception
{
if(firstname.getText().equals(""))
{
if(lastname.getText().equals(""))
{
}
else
{
throw new Exception();
}
}
else
{
throw new Exception();
}
}
This is my second class
boolean useTry = true;
try
{
vh.validateName(firstnameTextField, lastnameTextField);
firstnameTextField.setText(firstnameTextField.getText());
lastnameTextField.setText(lastnameTextField.getText());
}
catch (Exception e)
{
actiontarget.setText("Indtast et fornavn");
actiontarget.setText("Indtast et efternavn");
useTry = false;
}
if(useTry)
{
paymentPage();
}
The IF-statement just checks through the validations and when everything is OK it goes to the paymentPage. This is a booking system!
The problem is that it does NOT validate. When I click the "Create member" button I have made it just goes to the payment page, which it shouldn't, because no information have been made in the Firstname and Lastname TextField!
Hope you can help me !!
Regards
Alex
I think your if statement is reversed.
Don't want it to throw an exception if either field is empty?
Instead of
if(firstname.getText().equals(""))
{
if(lastname.getText().equals(""))
{
}
else
{
throw new Exception();
}
}
else
{
throw new Exception();
}
I think you want
if(firstname.getText().equals("") || lastname.getText().equals("")){
throw new Exception();
}
That being said, throwing a general exception isn't preferred. At the same time, Exception throwing is somewhat an expensive process execution wise. You could alter your code to just return a boolean of whether it's validated or not & then check that return value instead of throwing and catching exceptions. Just a thought.
I changed it to
if(methodName.getText().length() > 1)
{
}
The problem was that it HAD to be empty to success the validations... so stupid.
I'm trying to write a job scheduling system in GWT that maintains an array of exceptions (Class<? extends Exception>[] exceptions), that might be resolved by retrying the job. For this, if the scheduler catches an exception, I need to see if this exception matches one of the classes in the array. So, I would like to have a function like this:
boolean offerRetry(Exception exception) {
for (Class<? extends Exception> e: exceptions)
if (e.isInstance(exception)) return true;
return false;
}
Unfortunately Class.isInstance(...) isn't available in GWT.
Is there a good work-around for this? My current best guess is something like this:
public static boolean isInstance(Class<?> clazz, Object o) {
if ((clazz==null) || (o==null)) return false;
if (clazz.isInterface()) throw new UnsupportedOperationException();
Class<?> oClazz = o.getClass();
while (oClazz!=null) {
if (oClazz.equals(clazz)) return true;
oClazz = oClazz.getSuperclass();
}
return false;
}
Unfortunately, this approach does not support testing against interfaces, and I don't have any idea how to fix that either as Class.getInterfaces() is also not available. But would this approach at least work the same way as Java's Class.isInstance in all other cases, excluding interfaces? Specifically, if I look at GWT's source for Class.java, the getSuperclass() method contains a check of isClassMetadataEnabled(), which might return false (but I don't know in which cases), as it contains a comment saying "This body may be replaced by the compiler".
Or is there a better way entirely to do this?
I use following code:
public static <T> boolean isInstanceOf(Class<T> type, Object object) {
try {
T objectAsType = (T) object;
} catch (ClassCastException exception) {
return false;
}
return true;
}
Maybe something like this would help:
boolean offerRetry(Exception exception) {
try{
throw exception;
} catch (SpecException se) {
return true;
} catch (SpecException1 se1) {
return true;
...
} catch (Exception e) {
return false;
}
}
It depends on how you construct the array of exceptions. If the java 7 stuff works properly then you could put all exceptions in one catch:
boolean offerRetry(Exception exception) {
try{
throw exception;
} catch (SpecException | SpecException1 | ... se) {
return true;
} catch (Exception e) {
return false;
}
}
There is simple way to throw exception with message in java ?
In the following method I check for types and if the type doesn't exist i want to throw message
that the type is not supported ,what is the simplest way to do that ?
public static SwitchType<?> switchInput(final String typeName) {
if (typeName.equals("java.lang.String")) {
}
else if (typeName.equals("Binary")) {
}
else if (typeName.equals("Decimal")) {
}
return null;
}
Use the Exception Constructor which takes a String as parameter:
if (typeName.equals("java.lang.String")) {
}
else if (typeName.equals("Binary")) {
}
else if (typeName.equals("Decimal")) {
}
else {
throw new IllegalArgumentException("Wrong type passed");
}
The standard way to handle an illegal argument is to throw an IllegalArgumentException:
} else {
throw new IllegalArgumentException("This type is not supported: " + typeName);
}
And try not to return null if you can avoid it.
this method cannot throw an exception really
because typeName in input parameter of function is a String already..
I'm working on EJB client + server, and I wonder, how to deal with server data errors on client. Should I check return value on client or catch an Exception? Example, that use return value logic:
//server bean method
public int create(MyObj obj) {
int PKID = someDataService.create(obj);
return PKID;
}
//client
if(!(MyBean.create(obj) > 0)) {
showMessage("Can't create MyObj");
}
Example with exceptions:
//server bean method
public void create(MyObj obj) {
int PKID = someDataService.create(obj);
if(!(id > 0)) {
//only EJBExceptions will be delivered to client
throw new EJBException(new MyDataException());
}
}
//client
try {
MyBean.create(obj);
}
catch(EJBException e) {
if(e.getCause().getClass.equals(MyDataException.class)) {
showMessage("Can't create MyObj");
}
else {
showMessage("Some boring error occurred");
}
}
I know, that return value checking instead of exceptions looks like coding in C, but all this EJB thing confuses me. Which is the better way?
Throw exception from your method
public void create(MyObj obj) throws MyDataException
and annotate your custom exception with ApplicationException
#javax.ejb.ApplicationException
public class MyDataException extends Exception
{