0

I have the following code:

try {
  double a = Double.parseDouble(args[0]);
  if(a <= 1) {
    ...
    System.exit(-1);
  }
} catch(Exception e) {
  ...
  System.exit(-1);
}

With my solutuion i have to write the same code twice. Is there a way to go to the catch block (like making an error on purpose) or is there another way to simplify this code?

Leon
  • 35
  • 5
  • 3
    You could throw the exception you want to catch manually i.e. `throw new Exception("Number too small");` – Turamarth Nov 28 '19 at 15:24
  • 1
    It is not recommanded to either throw an ```Exception``` or catch an ```Exception```. Try to be more precise in both your catch clause and throw clause. Try to understand classes hierarchy starting from throwable. – D. Lawrence Nov 28 '19 at 15:31

1 Answers1

3

It is possible to programmaticaly throw an error

try {
  double a = Double.parseDouble(args[0]);
  if(a <= 1) {
    throw new Exception("some error happened");
  }
} catch(Exception e) {
  ...
  System.exit(-1);
}
Nicolas
  • 8,077
  • 4
  • 21
  • 51
  • I wouldn't use exception throwing for the normal flow of execution. It's all in the name: an exception should be exceptional – D. Lawrence Nov 28 '19 at 15:34
  • @D.Lawrence I don't agree, an exception is when an error is appening and you want to stop the current processing to handle that exception. In case of OP's code, they are using `System.exit()`, so they want to stop the current execution instantly. – Nicolas Nov 28 '19 at 15:37