Ec (2); warn sets the error level to: error_reporting (e_all | e_strict); array variable undefined will also report an error, in fact, very good, but sometimes do not need to report this error, the solution of the php tutorial is: @ $ _ get [unkown]; so that the error prompt can be placed. exception: thrownewexception (& quot; usernamealreadytaken & quo script ec (2); script
Warn: Set the error level to error_reporting (e_all | e_strict );
If the array variable is undefined, an error is returned. In fact, it is quite good, but sometimes this error is not required. The php tutorial solution is as follows:
@ $ _ Get ['unkown '];
In this way, the error message is displayed.
Exception:
Throw new exception ("username already taken ");
In other cases, if you think that the client does not want to use too many operations but only want to see the exception information, you can throw an unchecked exception:
Throw new runtimeexception ("username already taken ");
In addition, you can provide a method to verify whether the username is occupied.
It is necessary to reiterate that the checked exception should allow the client to obtain rich information. To make your code more readable, you may prefer to use unchecked excetpion to handle errors in your program (prefer unchecked exceptions for all programmatic errors ).
4. document exceptions.
You can use the javadoc's @ throws tag to indicate that (document) Your api will throw a checked exception or unchecked exception. However, I prefer to use unit tests to explain (document) exceptions. No matter which method you use, you need to let the client code know the exception to be thrown in your api. Here is an example of indexoutofboundsexception testing:
Public void testindexoutofboundsexception (){
Arraylist blanklist = new arraylist ();
Try {
Blanklist. get (10 );
Fail ("shocould raise an indexoutofboundsexception ");
} Catch (indexoutofboundsexception success ){}
}
The above code will throw indexoutofboundsexception when requesting blamklist. get (10). If it is not thrown, the fail ("shocould raise an indexoutofboundsexception") is displayed, indicating that the test failed. By writing unit tests with test exceptions, you can not only see how exceptions work, but also make your code more and more robust.
The authors below will introduce best practices for using exceptions)
1. always do some cleanup (always clean up after yourself)
If you use resources such as database tutorial connection or network connection, remember to do some cleanup work (such as closing the database connection or network connection). If your api throws an unchecked exception, then you need to try-finally for necessary cleanup:
Homepage 1 2 3 last