Java (or programming in general): When to use exceptions?

Status
Not open for further replies.

C0rinthian

Ars Tribunus Angusticlavius
6,858
Hello! Pretty new to programming in general, and in working on a class assignment (data structures) I've hit a scenario where I'm not sure what is the best way to proceed.

Say we're creating an object with a String attribute. Now say, we want to make sure this String attribute is never an empty string. It looks like I can handle this two ways:

1) check the input prior to creating the object, like so:
Code:
public class TestIfElse {

   private String name;
   
   public TestIfElse(String name) {
       this.name = name;
   }
   
   public static void main(String[] args) {
       String input = "";
       if ( input.isEmpty() ) {
           System.out.println("The name must not be empty");
       } else {
           TestIfElse thing = new TestIfElse(input);
       }
   }
}

2) Have the constructor throw an exception if the String it's passed is empty:

Code:
public class TestException {

    private String name;
    
    public TestException (String name) {
        if (name.isEmpty()) {
            throw new IllegalArgumentException("name can not be empty");
        }
        this.name = name;
    }
    
    public static void main(String[] args) {
        String input = "";
        try {
            TestException thing = new TestException(input);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

So I guess my question really is: Do we use exceptions to check business logic? Or is that something that should be kept outside the scope of the object itself?
 

ChaoticUnreal

Ars Tribunus Angusticlavius
7,989
Subscriptor++
Check before attempting to create the string and then check again when creating the string but don't throw an exception return false or return nil and check for not nil after creating it to display the message.

when doing error checking I like to go on the assumption that anyone else writing code is a fucking moron and didn't check anything. That includes myself from other classes (partially because you never know when someone will reuse your class later)
 

Ardax

Ars Legatus Legionis
19,794
Subscriptor
Do we use exceptions to check business logic? Or is that something that should be kept outside the scope of the object itself?
You use both. The exception helps enforce the object's contract, but the UI can prevent the exception from being raised and give the user more useful feedback.

string but don't throw an exception return false or return nil
How do you do that in a constructor or property setter?

when doing error checking I like to go on the assumption that anyone else writing code is a fucking moron and didn't check anything. That includes myself from other classes
This I agree with. Things that "can't ever happen" always manage to.
 

dragonlord

Ars Scholae Palatinae
1,123
Generic for all programming languages

Exception handling should be for exceptions. If you can avoid it (by testing your variables) do so as there are hidden overheads with exception processing that can mount up if you're handling an exception inside a loop.

Saying that if you are using exceptions then you should handle them at the highest useful level that you can recover from. If your language supports it, then also don't be afraid to catch and re-throw an exception tidying up the variables/state as you go.

Last point, if you do catch an exception try to log the details of the exception to a log file (including stack trace if you can) as knowing when and where an exception occured can be invaluable when you're trying to reproduce/fix it later.

In your example I'd generally check for valid input from main() before doing anything else as when you're writing larger programs it may take some time for easily tested invalid input to cause the program to go wrong.
 
It's not uncommon for amplified exception types to be used to communicate validation failures. Before I used APIs where it was prevalent, I thought it was kind of a hideous idea "you don't use exceptions for flow control!".

After using them, I prefer that to returning a boolean (someone, possibly you, will forget to check the bool returned) or muddying every method in the call chain with out parameters.

Code:
try {
  whatever.Validate();
}
catch (ValidationException e) {
  foreach(var errorMessage in e.ValidationResults) {
  }
}
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
Good info!

So the thought process I settled on was that even though my intended usage for the object would have some 'business rules' (like no empty strings) it was not necessarily appropriate to assume all theoretical users of the object would desire the same restriction. So I limited any checking within the object class to things that would cause unexpected behavior from the object itself, and left the responsibility of imposing business rules to the caller.

Then, when creating a new object elsewhere, I used a validator method that worked like the following:

Code:
public class TestObject {

   private String name;
   
   public TestObject(String name) {
       this.name = name;
   }
}

public class RunApp {

	public static TestObject validateInput(String name) {
		if (name.isEmpty()) {
			throw new IllegalArgumentException("Name cannot be empty");
		}
		return testObject(name);
	}
	
	public static void main(String[] args) {
		TestObject test;
		String input = "";

		try {
			test = validateInput(input);
			} catch (IllegalArgumentException ex) {
				System.out.println(ex.getMessage());
			}
		}
	}
}

So now the TestObject class doesn't care about anyone's business rules, it only cares that it gets valid input. Thus is can be used in multiple business cases without modification. The class for the app itself (in my actual project, the class generating the UI) then has a validator method that checks inputs before passing them to the constructor.

Does this look like a good way to handle this kind of interaction? (Its very simplified here, but conceptually it maps)
 

dragonlord

Ars Scholae Palatinae
1,123
in your example it would probably be better to return null from the ValidateInput method and test for a null return value. I may also add an out/by reference variable to the arguments list of ValidateInput so that you can test for every incorrect value and give the user a list of things that are wrong rather than them having to solve every problem sequentially.

e.g. - Note not a java programmer so really pseudo code

Code:
public function ValidateInput(String name, byRef String reason) as TestObject
       if(name is null)
       {
            reason = "Name cannot be null"
            return null
       }
       if(name.isEmpty()) 
           reason = "Name cannot be empty"
       if(name.startsWith(number)) 
           if(reason is Null)
               reason = "Name cannot start with a number"
           else
               reason += "\nName cannot start with a number"
       if(name.count > 32)
           if(reason is null)
               reason = "Name to0 long"
           else
               reason += "\nName too long"
       if(reason is not null)
          return null
       return new TestObject(name)
end function

public shared sub main(args() as object)
    dim test as TestObject
    dim input as String = ""
    dim failReason as String = ""
    try
        test = ValidateInput(input, failReason)
        if(test is null) {
            MessageBox(failReason)
            return
        }
    catch ex as exception
        MessageBox(ex.message)
    end try
end sub
 

dragonlord

Ars Scholae Palatinae
1,123
You could always return an array of Object and if it's length > 1 then show the second item in the array as a message. Or even better pass in an argument Object

Code:
private class ArgObject
     public property Parameter
     public property FailReason
end Class

And then if your check is null use the fail reason of the passed in class.

Most languages use a similar feature for cancelable events.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
Throw on Validate is an incredibly common and incredibly stupid pattern. What if there is more than one validation error? The client keeps fixing one error and retrying until they get it right? What if you need to log the value of Field12 on every request but Field3 was invalid?

Return a list of validation errors. Fail validation if list is not empty. Use the list of *multiple* errors to give useful messages to the caller.

Finally, receiving invalid data from a client is not exceptional. It's incredibly common.
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
[url=http:/civis/viewtopic.php?p=25273207#p25273207:2l9rnjkb said:
Pont[/url]":2l9rnjkb]Throw on Validate is an incredibly common and incredibly stupid pattern. What if there is more than one validation error? The client keeps fixing one error and retrying until they get it right? What if you need to log the value of Field12 on every request but Field3 was invalid?

Return a list of validation errors. Fail validation if list is not empty. Use the list of *multiple* errors to give useful messages to the caller.

Finally, receiving invalid data from a client is not exceptional. It's incredibly common.

This makes a ton of sense. Going to see how I would implement this later tonight.
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
[url=http:/civis/viewtopic.php?p=25273485#p25273485:2gxe6y4b said:
dragonlord[/url]":2gxe6y4b]The same way I did, except use a collection instead of building a string. And your passed in object would have an add error method.

The assignment I'm working on now explicitly forbids the use of ArrayList or Collections. They want us to suffer through Arrays first. I'll still try working with that later for my own purposes, but it wasn't on my radar initially.
 
[url=http:/civis/viewtopic.php?p=25273207#p25273207:153ehorx said:
Pont[/url]":153ehorx]Throw on Validate is an incredibly common and incredibly stupid pattern. What if there is more than one validation error?

What if you, say, used an exception object that could hold multiple validation errors in it? And then you could, like, catch that typed exception in places where you need to, like, do further validation checks and then concatenate your list of failures and hand that back to your caller?

Working with an application where validation happens in multiple places (since you have classes that handle intra-object validation and separated concerns that handle different aspects of inter-object validation), there ends up being (speaking from painful experience) a lot of boilerplate to collect all the things that can fail in a sane way or a tendency to have poorly separated validation concerns, which is a pain all its own.

Which is not to say that this is a golden hammer approach, but calling it stupid out of hand is on the short-sighted side.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
What if you, say, used an exception object that could hold multiple validation errors in it? And then you could, like, catch that typed exception in places where you need to, like, do further validation checks and then concatenate your list of failures and hand that back to your caller?
:scared:

Using exceptions as flow control? If you're defining exceptions, why not just
Code:
return new CustomValidationErrors("foo was not between baz and bazzle");

Working with an application where validation happens in multiple places
a) fix that
b) pass around the bag of validation errors and keep filling it

but calling it stupid out of hand is on the short-sighted side
It's born of years and years of experience.

Throwing exceptions for API calls is one thing. Throwing exceptions for user input or web service client validation is just wrong. Users and clients passing you bad data is entirely unexceptional.
 
[url=http:/civis/viewtopic.php?p=25276015#p25276015:2rd7zb8f said:
Pont[/url]":2rd7zb8f]Throwing exceptions for API calls is one thing.

Indeed, and that's what I'm talking about.

Of course, I've been doing a genuinely shitty job of it by using a super simple whatever.Validate() method as my example (where, agreed, it should be returning a list of validation errors for someone else to do something with).
 
Status
Not open for further replies.