Use if, exception, or assert? -- Read the javaeye forum post: interview question: exception or if judgment.

Source: Internet
Author: User

Today, I saw a very popular post on javaeye. The question is (interview): whether to use exception (exception) or if to judge 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 processing in the method does not affect the method function, use if else for processing. If the method fails to work due to incorrect parameters, an exception is thrown, java provides Java. lang. illegalargumentexception, which can be directly thrown by a new one. This is a runtimeexception and does not require try-catch.

2) mercyblitz: the advantage of the IF-else method is 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 low semantic meaning. It is not easy to track errors or prompt fewer errors, and has a single type (for example, the native type of C language is used) or it is difficult to unify (such as the C language structure and macro definition ).

The benefits of the exception method are that the business logic and exception handling are separated (the code 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 of all, you must 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? In addition, 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 handles parameter verification with exceptions.

6) liupopo: first, identify what an exception is. Exceptions are abnormal during program execution. If there is any incorrect data or logic, an exception is thrown.

If else is a logical judgment that controls the program flow.

Assertions are clear conditions such as the values and types that should be pre-determined.

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 foreseeable runtime exceptions, such as null pointers. Generally, the NULL pointer is judged not by capturing nullpointerexception, but by using a judgment statement before calling the object. For example:

View plaincopyprint?
  1. // If list is not checked for null, a null pointer exception is thrown when list is null.
  2. If (null! = List & 0 <list. Size ()){
  3. For (INT I = 0; I <list. Size (); I ++ ){
  4. }
  5. }

// If list is not checked for null, a null pointer exception is thrown when list is null. <br/> If (null! = List & 0 <list. size () {<br/> for (INT I = 0; I <list. size (); I ++) {<br/>}< br/>

2. Do not use exceptions for frequent and predictable events

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


A logic is self-controlled and clear


A requires too much if-else when the situation is complex, making the logic hard to understand.

B is prone to vulnerabilities, leading to errors or unexpected results



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.


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) 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. When the value is null (in violation of the syntax of the Java language), nullpointerexception is automatically thrown by 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:

View plaincopyprint?
  1. If (S = NULL ){
  2. Throw new numberformatexception ("null ");
  3. }

If (S = NULL) {<br/> throw new numberformatexception ("null"); <br/>}< br/>

There are many restrictions on the radix parameter, so the source code makes a few if judgments:

View plaincopyprint?
  1. If (Radix <character. min_radix ){
  2. Throw new numberformatexception ("Radix" + Radix + "less than character. min_radix ");
  3. }
  4. If (Radix> character. max_radix ){
  5. Throw new numberformatexception ("Radix" + Radix + "greater than character. max_radix ");
  6. }

If (Radix <character. min_radix) {<br/> throw new numberformatexception ("Radix" + Radix + "less than character. min_radix "); <br/>}< br/> If (Radix> character. max_radix) {<br/> throw new numberformatexception ("Radix" + Radix + "greater than character. max_radix "); <br/>}< br/>

There are several other judgments.

Summary: in the Forum, someone mentioned that in the JDK source code, we often see similar

View plaincopyprint?
  1. If (S = NULL ){
  2. Throw new numberformatexception ("null ");
  3. }

If (S = NULL) {<br/> throw new numberformatexception ("null"); <br/>}< br/>

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 ensure 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 by yourself (this is the case 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, the checked
Exception is unnecessary, and the thrown uncheck exception does 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 (not an API provided to other developers), the 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 invalid 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 you receive a date parameter and then return a corresponding string type displayed on the page (this parameter is not required, such as birthday), if the date parameter is null, we should not throw nullpointerexception, but use if to make the following judgment:

View plaincopyprint?
  1. If (date = NULL ){
  2. Return "";
  3. }

If (date = NULL) {<br/> return ""; <br/>}

The returned Null String is reasonable, so that the page will be blank (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. I found a very interesting article on the Internet. He criticized Java's assert (the assert keyword of the Java trap). If you are interested, you can 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 the class on which to enable assertions (enable assertions without 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 class initialization is complete, the asserted state (enabled or disabled) cannot be changed.

However, an exception is mentioned in the Specification: the loop between class hierarchies (which is hardly the case in practice ). The example program is as follows:

View plaincopyprint?
  1. Public class Foo {
  2. Public static void main (string [] ARGs ){
  3. Baz. testasserts ();
  4. // Will execute after Baz is initialized.
  5. }
  6. }
  7. Class bar {
  8. Static {
  9. Baz. testasserts ();
  10. // Will execute before Baz is initialized!
  11. }
  12. }
  13. Class Baz extends bar {
  14. Static void testasserts (){
  15. Boolean enabled = false;
  16. Assert enabled = true;
  17. System. Out. println ("asserts" + (Enabled? "Enabled": "disabled "));
  18. }
  19. }

Public class Foo {<br/> Public static void main (string [] ARGs) {<br/> Baz. testasserts (); <br/> // will execute after Baz is initialized. <br/>}</P> <p> class bar {<br/> static {<br/> Baz. testasserts (); <br/> // will execute before Baz is initialized! <Br/>}</P> <p> Class Baz extends bar {<br/> static void testasserts () {<br/> Boolean enabled = false; <br/> assert enabled = true; <br/> system. out. println ("asserts" + (Enabled? "Enabled": "disabled"); <br/>}< br/>

After debugging, you will find that when the assert is not enabled, the result of the first output shows that the assert is enabled. Of course, the second statement is not enabled (Note: 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 first executed, assert enabled = true for single-step debugging; 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

We do not recommend capturing the assertionerror thrown by assert.

Since assertions may not be enabled, the program must not assume that the expressions in the assertions will be calculated, that is, they cannot rely on the asserted settlement result (the value of expression 1). Therefore, 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.

Summary and assertions can be found on the Internet: (list 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, there must be corresponding parameter checks 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 must 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.

Contact Us

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: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.