Many a time when I'm debugging I feel quite lazy and often want to stop execution of code within a method before that method actually ends. The naive solution is to put in a return statement or throw an exception at the point where you want to stop running your code. Of course this doesn't work if you have lines of code after your return/throw clause.
The compiler will throw an error if you try this...
error: unreachable statement
...and a mandatory screenshot of the error...
Now you may be tempted to simply comment out the remaining lines, but depending on how much code you've got that could be more effort that it's worth.
So here's my solution to this. Put in an if statement
that always evaluates to true and in the body of this statement either return from the method or throw an exception. This is a simple non-intrusive short circuit of the code, just remember to remove it when you're done with your debugging!
It looks something like this...
Now the compiler will not complain and your code will exit early as required.
Hope you found this post useful...
...so please read on! I love writing articles that provide beneficial information,
tips and examples to my readers. All information on my blog is provided free of
charge and I encourage you to share it as you wish. There is a small favour I ask in return however -
engage in comments below, provide feedback, and if you see mistakes let me know.
If you want to show additional support and help me pay for web hosting and
domain name registration,
donations, no matter how small, are always welcome!
Use of any information contained in this blog post/article is subject to this disclaimer
Other posts you may like...