Atitit. Architecture Design-whether the method call result is abnormal or the return value
1. Should Return bool type or exception 1
2. There will eventually be four situations: throwing an exception, returning special values, blocking, timeout 1
3. Advantages and Disadvantages of exceptions 1
4. Java blockingqueue prompt 2
5. Solution: use both. One API returns bool and one throw exception... 2.
1. the bool type or exception should be returned.
Now I have a problem. I have a function. The function to be implemented is to start a thread and then let the thread monitor an event.
But should I return bool type or exception?
Author: old wow's paw attilax iron, email: [email protected]
Reprinted please indicate Source: http://blog.csdn.net/attilax
2. There will eventually be four situations: throwing an exception, returning special values, blocking, and timeout
3. Advantages and Disadvantages of exceptions
The major benefit of exceptions is that you can bring more information to the exception classes, and you can design a clear exception class inheritance system.
However, sometimes the Korean bool is more convenient... when the if statement blackheads...
4. Java blockingqueue Tip 5. Solution: use both. One API returns bool and one throw exception...
|
First, let's take a look at the common methods provided by blockingqueue:
|
An exception may be reported. |
Returns a Boolean value. |
Possible Blocking |
Set the wait time |
|
Join |
Add (E) |
Offer (E) |
Put (E) |
Offer (E, timeout, Unit) |
|
Team-out |
Remove () |
Poll () |
Take () |
Poll (timeout, Unit) |
|
View |
Element () |
Peek () |
None |
None |
Well, you will understand the source code better. Take the arrayblockingqueue class as an example:
For the first method, it is obvious that an exception is thrown if the operation fails. In addition, we can see that the second type of method is actually called. Why? Because the second method returns Boolean. Java code
1 Public Boolean add (E ){
2 If (offer (e ))
3 return true;
4 else
5 throw new illegalstateexception ("queue full"); // The queue is full and an exception is thrown.
6}
7
8 Public E remove (){
9 E x = poll ();
10 if (X! = NULL)
11 return X;
12 else
13 throw new nosuchelementexception (); // The queue is empty and an exception is thrown.
14}