I am confused about what is considered a good practice - is this decision language dependent? Suppose I have the following Java code:
public class Stack {
public Integer pop() {
if (isEmpty()) return null; // or some exception maybe?
// else get and return the top item in the stack.
};
}
}
The client of the pop
method expects some Integer
value, so what would be the best approach to let the client know that the stack is empty?
It's not possible to both throw an exception and return a value from a single function call. Perhaps it does something like returning false if there's an error, but throwing an exception if the input is invalid.
You can throw an exception in Java by using the throw keyword. This action will cause an exception to be raised and will require the calling method to catch the exception or throw the exception to the next level in the call stack.
Exceptions shouldn't be returned as a return value or parameter instead of being thrown. Don't throw System. Exception, System. SystemException, System.
You'd throw an exception because you anticipated wrong usage without the support of contracts. For example, and IndexOutOfRange exception anticipated a negative index value. If you really don't want a calling method to ignore your error you need to throw an exception.
When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.
Returning null
or a default value is usually a bad practice and an exception should be preferred. The reason is that you should always strive to fail as fast as you can when something goes wrong. If you return null
instead, you will get errors happening in some other place in the code and users of your API will have trouble finding where the problem was. This is called Fail Fast.
An exception to this rule of thumb is when your API will make users rely on exceptions for flow control, so if your stack does not support isEmpty()
, an exception is not a good idea here. If you have a stack that can allow only peek()
, pop()
, and add()
- for some reason, isEmpty()
is not allowed to be part of the API.
What will happen to the code of your users for both approaches?
Option 1 - Using null
:
Integer x = stack.pop();
if (x != null) {
//do something with x
}
Option 2 - Using exceptions:
Integer x = null;
try {
x = stack.pop();
} catch (MyException e) { }
//do something with x
The second is actually using the exceptions mechanism for flow control - which is a big flaw in API design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With