5

I'm testing a batch script, to check that it's handling any errors when a compiled jar is run.

What's the simplest snippet of a code I can add to my java to cause a runtime error?

3 Answers 3

13

You can simply throw a RuntimeException:

throw new RuntimeException("Test runtime exception");
Sign up to request clarification or add additional context in comments.

3 Comments

How do I insert this without getting a unreachable statement compilation error?
The way I did it was by just replacing everything that was in the main block with your snippet. Works for what I'm doing.
put an if (true) statement before it
0
for (int i=0; i<1; i++){
  int x = 10/i; // Arithmetic exception
}

3 Comments

Seems like a rather convoluted way to do something so simple.
Put if(true) instead of loop, if you like. Just some another way of doing wht OP wants :)
Ideally any such code is hardwaired and difficult to remove without recompiling later. Just for testing a jar file, I would pass an argument through cmd line and induce an exception conditionally while testing.
-1

declare x before for loop then type x=10/i;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.