I see lots of questions about how to make Intellij break on exceptions. I'm trying to do something different: I want to throw an exception at a breakpoint so that I can see what will happen if an exception were to occur at that code.
I've figured out ways to force this. For example, if I have a variable called willBeUsed
, I can hit a breakpoint and add a watch that says willBeUsed = null
. This will trigger a NullPointerException eventually.
But I'm in a situation where I want to throw an IOException
to see what happens. There's no way to trick my code into doing that. When I add a watch that says throw new IOException()
it gives me an error saying, "unexpected tokens".
As a work around, I can modify the code to throw the exception and redeploy. But I'm wondering if there's a way to do this in the debugger without modifying source code.
Add a condition to a breakpoint when debugging. Right-click on a breakpoint to configure its behavior: for instance, you can add a condition so that the execution will only be stopped when that condition is met.
Ctrl + F8 (Mac: Cmd + F8) Toggle breakpoint.
If you press and hold the Ctrl / ⌘ button while dragging the arrow, the IDE will highlight all the lines in green. When you drop the arrow, you won't jump to the line of code. Instead, the IDE will act as if you have used the Run to Cursor (⌥F9) action.
You can right-click on stacktrace and choose 'Throw Exception'
(Since 2018.1 version. See JetBrains issue: IDEA-148408)
How about placing the throw
statement in an if
block, and only change the condition, e.g.:
boolean shouldThrowException = false; // .... if ( shouldThrowException ) //place breakpoint here { throw new IOException(); }
When you hit the breakpoint, change the value of shouldThrowException
to true.
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