Use if, Exception, or assert?
-- Read the JavaEye forum post: interview question: Exception or if judgment
Today, I saw a very popular post on JavaEye. The question is: interview question: whether to use Exception or if to judge http://www.javaeye.com/topic/745640. The content is probably:
When the parameter is invalid, is it true that if else determines whether to return a value or an Exception directly?
What are the advantages of if else?
What are the advantages of exception?
Or is it determined based on different situations?
In practice, if else or Exception should be used, so the following replies are also different. Many people have some truth. Here, I will first list several reliable replies:
1) sam_chi: Check the situation. if the method can be processed without affecting the method function, use if else for processing. if the method fails to work due to a parameter error, you have to throw an exception, java provides java. lang. illegalArgumentException, which can be directly thrown by a new one. This is a RuntimeException and does not need to try .. catch.
2) mercyblitz:The advantages of the if-else method are that it is closer to logical thinking and has better performance than Exception. Compared with Exception, it is not suitable for OOP and has a non-obvious semantics. It is not easy to track errors or have fewer error prompts, and has a single type, such as using the native type of C language) or it is difficult to unify such as the C language structure and macro definition ).
The benefits of the exception method are that the separation code of the business logic and exception handling is relatively clear). try to process the business and catch to process exceptions. In API design, Exception Handler can be designed to handle exceptions, so that the layers are clear. At the same time, better OOP encapsulation and polymorphism. The disadvantage is that the performance is relatively poor.
3) fireaap:Select if... else or exception as needed. The basis for selection is the responsibility of your method. It can also be said that it is the contract of your method.
4) konser:Sam_chi is right. First, you need to understand what is an exception. Exceptions are caused by program failure, incorrect api call methods, resource failure, and so on. The program logic is the same thing. Why do we need to mix exceptions with logical judgments for comparison? If the parameter is invalid, IllegalArgumentException is thrown.
What are the advantages of if else?
Invalid parameters cannot be executed normally. What are the advantages of this statement?
What are the advantages of exception?
The object-oriented thinking can be handled in different ways when each exception is thrown. The disadvantage is that the creation consumes memory and the efficiency is low.
5) IcedCoffee:The definition of the java specification is that exceptions should not be involved in the control process. You cannot regard exceptions as a normal control process as part of the program. This is wrong.
This is what the interviewer really wants to take ..
No company will handle parameter verification with exceptions ..
6) liupopo:First, we need to clarify what an exception is. Exceptions are some abnormal situations during program execution. If there is any incorrect data or logic, an exception will be thrown.
If else is a logical judgment that controls the program flow.
Assertion is a clear condition that determines in advance what value should be and what type should not be.
It is not very well defined to distinguish how to use these features. However, we can consider the usage scenarios. The following may not be very accurate, but you can refer to the following:
Exception: A programmer writes a method to another programmer. For example, if someone else uses this method, it may not work as expected, this may cause abnormal processing of my methods. At this time, I need to use exceptions, and I can decide to handle exceptions by myself (in catch statements) or to the caller for processing (throwing an exception directly)
If else is the method I wrote. To make logical judgments, use it. There is nothing to say.
The asserted availability is too large. I am calling methods written by others, or the data I obtain through other channels when processing the program (such as the return value of calling others' methods (as if I do not recommend using assertions), passed in through the parameter) and so on. It is a syntax element provided for convenient development and debugging.
7) JonyUabka:1. Capture and handle unforeseen runtime exceptions, such as null pointers. Generally, the NULL pointer is judged not by capturing NullPointException, but by using a judgment statement before calling the object. For example:
// If list is not checked for null, a null pointer exception is thrown when list is null.
If (null! = List & 0 <list. size ()){
For (int I = 0; I & lt; list. size (); I ++ ){
}
}
2. Do not use exceptions for predictable events that often occur.
3. Do not use exceptions to implement the control structure.
4. The general idea is to only handle errors with exceptions: logic and programming errors, Setting errors, corrupted data, resource depletion, and so on.
Java coding specifications are described in detail. I want the examiner to answer this question.
8) maomaolingyu:
If else
Advantages:
A logic is self-controlled and clear
Disadvantages:
A. Too much if else is required when the situation is complex, making the logic hard to understand.
B is prone to vulnerabilities, leading to errors or unexpected results
Exception
Advantages:
A exceptions are propagated through the exception chain and automatically captured by jvm to reduce the logic code.
B exceptions make it easy to determine the code problem section for testing.
Disadvantages:
A When an exception occurs but is not captured correctly, the exception is thrown to the user page.
I have cited so many references. Let's talk about some of my views below. please correct me for any mistakes.
First, you should not answer this question: use Exception or if to judge, but use Exception or if as needed. I personally think that the interviewer is very important to your understanding of exceptions. The key to the answer should be the advantages and disadvantages of the two and their applicability. By the way, we can summarize how you handle exceptions in practice. I disagree with some people who say that assert is a standard answer. As someone replied: the question is: whether to use Exception or if to judge, but to use an assertion, it's too far from the question. In this case, how can I answer the following questions? Are they not good, assert is good?
I think liupopo is reliable. The following code is used to illustrate some problems.
Before that, as many people have said, we need to clarify what Exception is. The Java Language Specification 3.0 contains the following description: When a program violates the semantic constraints of the Java programming language, the Java virtual machine signals this error to The program as an exception. when a program violates the semantic constraints of the Java language, the Java Virtual Machine will send this error exception to the program.
Enter the subject below:
1. Check how Java APIs are processed.
I checked the source code of the DateFormat, Integer, and other classes. The analysis is as follows:
1.1 public final String format (Date date) Method
The date parameter of this method is incorrect only when it is null. However, the source code does not determine whether the parameter is null. If it is null, it violates the syntax of the Java language. The NullPointerException is automatically thrown by the JVM instead of throw by the API.
1.2 public static Integer valueOf (String s, int radix) throws NumberFormatException Method
This method has two parameters, the first String type parameter may be null, and the method declaration throws a NumberFormatException, so there is a if judgment:
If (s = null ){
Throw new NumberFormatException ("null ");
}
There are many restrictions on the radix parameter, so the source code makes a few if judgments:
If (radix & lt; Character. MIN_RADIX ){
Throw new NumberFormatException ("radix" + radix +
"Less than Character. MIN_RADIX ");
}
If (radix> Character. MAX_RADIX ){
Throw new NumberFormatException ("radix" + radix +
"Greater than Character. MAX_RADIX ");
}
There are several other judgments.
Summary: in the Forum, someone mentioned that in the JDK source code, we often see similar
If (s = null ){
Throw new NumberFormatException ("null ");
}
Such code. By using liupopo, the JDK method is written to Java programmers for calling, and Java has its own internal exception mechanism. For example, for the NullPointerException thrown by the format () method, JDK cannot handle it by itself. The exception is: This method is not used on its own, to use this method, we should ensure that the input Date parameter is not null, that is, if judgment is required, which is the same for the valueOf method, before calling a method, you should determine whether the value is null or make sure that the value is not null ). From the JDK's radix parameter processing method, we can see that if is often used in combination with Exception, if is used in processing logic, and Exception is used to tell the user that there is a problem ". Therefore, if the code you write is used by others, you need to consider whether to throw an exception. In this case, JDK should be used to determine more parameters: for invalid parameters, if, after judgment, it is packaged as a unified Exception throw. Of course, exceptions may not need to be thrown, but are handled in various open-source frameworks ).
2. The currently recommended Java exception Mechanism
During the design of Java APIs, a large number of checked exceptions were used. At that time, this method was recommended. However, anyone who has used Spring knows that Spring uses unchecked exception (RuntimeException) in a large number. Bruce Echel, author of thinking in java, said: "when there is a small amount of code, the checked exception is undoubtedly a very elegant concept and helps avoid many potential errors. However, experience shows that the results are the opposite for a large number of codes ". In many cases, programmers do not know how to handle exceptions thrown by Java APIs, such as SQLException. printStackTrace (), or do nothing, which leads to a lot of try... catch ..., in this case, it is unnecessary to throw a checked exception and the uncheck exception will not pollute the interface. It is necessary to study the problem of exception handling.
Since it is recommended to use uncheck exception, combined with the characteristics of Exception itself, when writing an application is not provided to other developers for API), parameter judgment should be more use if, after all, there are not many parameter errors.
In addition, it is recommended that you use Java's IllegalArgumentException exception for judgment. Of course, this is also feasible sometimes. For example, in some cases, it is difficult to determine if the parameter is unable to live because we do not know what the illegal parameter will be). This exception can be used in this case.
In fact, in many cases, the return value of a method needs to be considered when checking the parameter validity. For example, if the Date type parameter is null, a corresponding String type is returned and the parameter is displayed on the page, for example, birthday, we should not throw NullPointerException, but use if to make the following judgment:
If (date = null ){
Return "";
}
The returned Null String is reasonable, so that the page will be blank, which is equivalent to not filled ). In other cases, if the returned value is of the boolean type, false may be returned if the parameter is invalid. Depends on the actual situation.
3. assert)
In the reply to the Forum, someone pushed assert to determine the validity of the parameter. I don't know if I didn't understand the meaning of the question, whether I didn't know enough about the assertions, or I have a special liking for the assertions. It is certain that assert is definitely incorrect. Assertions are only a tool for testing and debugging by programmers. They are generally not enabled after release, and Java specifications also recommend this. The validity of a parameter always exists, so assertions are totally false.
I have almost never used Java's assert, And it is rarely used. Test or Debug the program. Most of them use the Debug function of JUnit or IDE. They have worked very well. Find a very interesting article on the Internet, which is an assert keyword for java's assertJava trap. If you are interested, read it. I personally do not fully agree with this idea. Introducing assert in Java should be advantageous.
Here we will summarize The description of assert in The Java Language Specification 3.0.
3.1 assert syntax
The assert statement has two syntax forms:
Assert expression 1;
Assert expression 1: expression 2;
The value of expression 1 must be of the boolean type; otherwise, the compilation is incorrect. Here, the boolean type has two forms: 1) var1 = var2; 2) var = true. The second form of var is a boolean type. Generally, the first form should be used, while the second form is often caused by programmer errors. The value of expression 2 can be of any type except void.
3.2 When assertions are enabled
By default, assertions are not enabled. You can select which class to enable assertion to enable non-inheritance ). Before the class field initializer and static initializer initialize, the class loader of the Class determines whether to enable or disable Assertions based on the configuration. Once the class initialization is complete, the asserted state is enabled or disabled.
However, an exception is mentioned in the Specification: the loop between class hierarchies is hardly the same in practice ). The example program is as follows:
Public class Foo {
Public static void main (String [] args ){
Baz. testAsserts ();
// Will execute after Baz is initialized.
}
}
Class Bar {
Static {
Baz. testAsserts ();
// Will execute before Baz is initialized!
}
}
Class Baz extends Bar {
Static void testAsserts (){
Boolean enabled = false;
Assert enabled = true;
System. out. println ("Asserts" + (enabled? "Enabled": "disabled "));
}
}
After debugging, you will find that when the assert is not enabled, the first output result shows that the assert is enabled. Of course, the second statement shows that the assert is not enabled. If the assert is not enabled, assert enabled = true ). This indicates that when the assert statement is executed before class initialization, the result is as if assert is enabled. Polaris found a strange phenomenon during debugging: When the testAsserts method was executed for the first time, the single-step debugging, assert enabled = true; the statement seems to have jumped over, however, the result shows that the statement is executed. Very strange .)
About how to enable assertion, the console is enabled, and the IDE enables online search, which is not described here.
3.3 Precautions for using assertions
Java specification for the execution of asserted statements are described in detail, interested friends can refer to the http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10
We do not recommend capturing the AssertionError thrown by assert.
Because assertions may not be enabled, the program must not assume that the expressions in the assertion will be calculated, that is, it cannot rely on the value of the assertion settlement result expression 1, expression 1 may have some side effects:
1) Although the assert statement can have side effects, as mentioned in expression 1 above, return the second form of the boolean type. However, this is usually not suitable, this may lead to different results when assert is enabled or disabled;
2) do not use assertion as a parameter check for common methods. Parameters of common methods will always be executed. This can be a good explanation of why it is wrong to use assertions to determine the validity of a parameter, although assertions can sometimes be used to check the parameters passed to a private method.
When explaining the assertion side effects, the Java specification also says erroneous arguments shocould result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException or NullPointerException ), that is, the incorrect parameter check should generate an appropriate runtime exception.
I can see the summary and assertions on the Internet: list them for reference)
1) You can place assert false where the program is not expected to arrive under normal circumstances.
2) assertions can be used to check the parameters passed to the private method. For public methods, because they are provided to external interfaces, you must check the parameters in the methods to ensure code robustness)
3) pre-and post-conditions for execution using the assertion Test Method
4) Use assertions to check the unchanged state of the class to ensure that the state of a variable must be met under any circumstances. For example, the age attribute should be greater than 0 and smaller than a proper value)
3.4 Polaris suggestions
You can use IDE or JUnit for debugging or testing.
Having said so many hopes, I hope they will be helpful to you. If you do not have any mistakes, please criticize and correct them.
This article is from the "Xu Xinhua polaris" blog, please be sure to keep this source http://polaris.blog.51cto.com/1146394/383055