Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Intellij, how can I throw an exception at a break point?

Tags:

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.

like image 321
Daniel Kaplan Avatar asked Jun 13 '13 18:06

Daniel Kaplan


People also ask

How do I use conditional breakpoints in Intellij?

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.

How do I skip Debug points in Intellij?

Ctrl + F8 (Mac: Cmd + F8) Toggle breakpoint.

How do I skip a line while debugging in Intellij?

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.


2 Answers

You can right-click on stacktrace and choose 'Throw Exception'

enter image description here

(Since 2018.1 version. See JetBrains issue: IDEA-148408)

like image 188
Marek F Avatar answered Dec 01 '22 01:12

Marek F


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.

like image 38
MByD Avatar answered Nov 30 '22 23:11

MByD