"Deal with your anomalies."
-----------------
Exception handling is a very important part of Java programming. It is recommended that you read <effective Java programming Language guide> or <practical java> before using an exception;.
Here are a few suggestions from the book:
* Never ignore exceptions
* Never hide the abnormal * * *
* Use exceptions only if not normal
* Use check exceptions for recoverable conditions, use Run-time exceptions for program errors (runtimeexception)
* Make a document for the exception thrown by the method
* Include failure capture information in details
* Use finally to avoid resource leaks
*....
Here specifically, in the development of the case to deal with NULL, otherwise often caused nullpointexception exception, in Java this is one of the most troubling exception.
If your program has reported dozens of nullpointexception for a null value, it's not only annoying, but it's also very hard to find the error. So in Java you must pay attention to this problem.
If your function does not allow null values, then you can intercept it, throw an exception, or give the customer a more friendly hint, isn't it?
Let's take a look at an example:
Public String getName (User auser)
{
What happens if Auser is null
return Auser.getname ();
}
Obviously, if the argument is null, an exception is thrown. Should read:
Public String getName (User auser)
{
if (Null=auser)
{
Return "";
}
Else
{
return Auser.getname ();
}
}
Or you can ask for the argument not to be empty, and throw an exception that forces the user not to pass in a null value.
There are often overlooked is the difference between runtimeexception and ordinary exceptions, in Java, this is a special exception class, in the program if encountered this exception, the user can not intercept it, and if it is other common anomalies, you do not have to intercept it. Our code often writes:
Try
{
Your code here
}
catch (Exception e)
{
Do warn
}
In this case, all the anomalies were intercepted, including RuntimeException. In many cases, this is not the appropriate way to handle, we should only intercept the necessary exceptions, but should ignore runtimeexception.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.