A
A
Askell2012-07-30 18:25:07
Java
Askell, 2012-07-30 18:25:07

How to throw a RuntimeException at the line "double weight = 1.0;"?

There is the following method:

public static double weight(Some input params) {
  double weight = 0.0;
  try {
    weight = 1.0;
  } catch(RuntimeException error) {
    // some error handling logic here
    weight = 0.0;
  } 
  return weight;
}

Let me leave behind the scenes why the try block has degenerated into one line during the life of the project, I can only say that there is a set of classes with a template implementation of this method in the form of “try {} catch {}” and the task is to test the code inside the catch block.
Therefore, in fact, the question is, can this be done without changing the code of the method?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Mezomish, 2012-07-30
@Askell

I don't really understand what the problem is either. Set a forced throw new RuntimeException();, test the processing logic, and then remove the forced throwing of the exception.
Well, if you want to be absolutely “awesome and inflated”, then replace “weight = 1.0;” to “weight = _dataProvider.getWeightData()”, where in “normal” mode _dataProvider is an instance of the “correct” class (returning normal data), and in test mode it is an instance of a special test class that inherits the same interface, but instead of normal data throwing exceptions.
Just be careful with that, don't end up with " factory factory tool factory " :D

J
jorikburlakov, 2012-07-30
@jorikburlakov

To be honest, it's not clear what the question is? What is the problem?

A
agladkov, 2012-07-30
@agladkov

Maybe change localization?

B
barker, 2012-07-30
@barker

I finally understood that this is some kind of riddle like “without changing a single character, make the code crash”. It should have been more clearly defined then, otherwise people do not understand.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question