R
R
Roman Deniskin2021-09-11 19:55:46
Java
Roman Deniskin, 2021-09-11 19:55:46

How to handle an error in a float function in Java?

Good afternoon. I decided to switch from PHP to Java and ran into a trail. problem.
Example code: https://ideone.com/P0gcHY
There is a function with a float return type. In my example, this is the simpleOperation function. An object is passed to it - an expression. The result of the function execution must be a float number. I would like to check for the presence of the operation. In PHP, if the operation is not found, I would just return null. But since Java is a strongly typed language, you can't return null from a float function.
How can I solve this problem? There is an idea to wrap the entire function code in a try block and throw exceptions in erroneous places. But from this it turns out that each method should by default be wrapped in blocks with exceptions. Is it normal? Or is there an easier way to pass error states.
PS If you still throw exceptions, then how to catch them from the client code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-09-11
@romka123

In java there is a difference between primitives:
double, float, int, long
and their wrappers:
Double, Float, Integer, Long.
Primitives cannot be null, but wrappers are already objects, and they can.
So in your example you should probably use Float instead of float

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question