I'm writing a login class in c#, and I'm trying to be diligent about开发者_如何学Go throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!?
Exceptions are used to provide detailed information about the cause of a particular failure. If you simply let the code fail on its own you miss the opportunity to provide richer details about the actual cause of the failure.
Your users should not be seeing the information you add to your exceptions. Instead, consider adding a global exception handler that catches your detailed exceptions, logs the information, and then displays a friendly error message to your user.
Exceptions provide not only a detailed message in your logs about why the failure occurred (i.e. password was null in your example) but also call stack information that indicates the call chain that led to the exception. In a login form this is less important. However, in a multi-threaded asynchronous client/server application this can be critical.
This article contains many good guidelines: http://msdn.microsoft.com/en-us/library/ms229005.aspx
If you're the one creating the Exception, you shouldn't do anything with it.
Exceptions are your way of letting your consumers know that something went wrong that you can't properly recover from. You're giving them the chance to either correct the issue, log the error, or pass the Exception up the chain until something useful can be done with it.
To signal to the next level up of abstraction that there is a problem, and alter its logical flow to account for the problem.
The exception itself happens to prevent bigger problems in the future. If you just silently did nothing when you knew something happened that wasn't supposed to, the program calling your code might assume that the user's file got saved when it really didn't, which can obviously be worse than if it's able to tell the user, "I couldn't save your file."
The message you give to an exception is for other developers. If the program crashes during development, the developer should be able to see the stack trace and more easily figure out why something happened that wasn't supposed to. Ideally you'll be able to log errors in such a way that developers can see them even in production.
Exceptions usually indicate that the contract of the method has been violated. The client of the method cares about the exception and should handle them appropriately. When the contract is violated, the method itself usually cannot recover and cannot produce meaningful results. The exception indicates that no meaningful results is forthcoming.
In short, the point is to indicate that something which shouldn't have happened did indeed happen.
Exceptions are a way for code to notify callers of some kind of failure. The calling code can do whatever they want with it, like display an error message, suppress the exception and degrade gracefully, etc.
Elegant way of showing what they(Customers) did bad.
So. you've written an excellent program. this program has a possible fail point. if for whatever reason the part of the program fails you might still want to continue the rest of the program and either call explicit attention to failure, log it, or just keep on going.
I'm going to use a pseudo-code syntax, but you should be able to follow it:
var pw=$_POST['pw'];
var un=$_POST['un'];
try{
$sql="select lastlogin,access from users where un=q(/'$un'/) and pw= q(/'md5($pw)'/)";
$user=$db->getRow($sql);
if(!$user) {
//they don't exist
}else{
//process their login
}
}catch(Exception $e){
//we has a Database error. either my query s really screwed up or the DB is down. let's log it and exit this stream; service
$mylogger->log("Error while logging in using module $MODULENAME$ ".implode("<br/>",(array)$e));
exit;
}
If your function will throw an exception if it can't log in, then code which calls your function can assume that if your function returns, it's logged in. This will ease the amount of work the code has to do to handle the "login succeeded" scenario, in exchange for requiring more work in the "login failed" scenario. If code will sometimes be used in cases where failure is semi-expected (e.g. try logging in with one set of credentials; if that doesn't work, try some other set) and sometimes used when failure would be unexpected and unrecoverable, it may be helpful to either have a "throw on error" boolean flag, or else have separate "Login" and "TryLogin" methods.
The nature of exceptions is that they have to be explicitly ignored. Suppose you have this function:
bool authenticate ( String username, String password )
{
if ( invalid_password(password) ) {
return (false);
}
// ... perform authentication ...
}
Now, consider that this is part of some server, and that the server runs in a highly privileged context. If the calling code (the one that performs authorization) has some error in it's logic, it might unintentionally allow users to perform actions they are not normally allowed.
I would write the following function instead:
void authenticate ( String username, String password )
{
if ( invalid_password(password) ) {
throw new LoginFailed();
}
// ... perform authentication ...
}
Note that this is purely a defensive programming approach, and it is my preference within this context. This way, an error in login will most likely not allow the operation to keep executing.
精彩评论