静态分析自定义规则以强制执行未经检查的异常处理 [英] static analysis custom rule to enforce unchecked exception handling

查看:115
本文介绍了静态分析自定义规则以强制执行未经检查的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中创建了一个运行时异常,我想确保它被捕获在我的一个类中,这样整个程序不会在发生时爆炸(例如,如果有人删除了我想通过构建或静态分析工具中的某些操作使try/catch语句失败).不幸的是,由于Java没有强制我对此未检查的异常使用try/catch语句,因此无法在编译时强制执行它.(我无法将我的例外更改为已检查的例外).

我想知道是否可以通过使用checkstyle/pmd/findbugs自定义规则来在特定类中强制执行try/catch语句.(检查特定类中的特定方法是否对我的运行时异常具有try catch语句).

谢谢.

解决方案

Checkstyle,FindBugs或PMD(或其提供的程序包)中没有现有的检测器可以满足您的要求.因此,您将不得不自己动手.

无需实际编程即可解决此问题的最简单方法是编写 PMD XPath规则,它在类 Y 中查找方法 X 和一个在其下捕获运行时异常的 catch 块.

如果失败,那么自定义Checkstyle检查将是下一个最简单的方法,但是它需要一个小的方法一点编程,然后您将不得不在所有地方部署自定义检查.

您还可以按照另一个答案中的建议编写自己的FindBugs检测器,但是由于您将不使用任何特定的FindBugs功能(例如字节码分析),因此对我来说似乎有些矫kill过正.

I have a runtime exception that I have created in my project, and I want to make sure that it is caught in one of my classes, so that the whole program doesn't explode when it occurs (i.e. if anyone deletes the try/catch statement I want to know by having something in the build or static analysis tools fail). Unfortunately, as java doesn't enforce me to have the try/catch statement for this unchecked exception, there is no way to enforce it on compile time. (I cannot change my exception to be a checked exception).

I am wondering if there is any way to enforce a try/catch statement in a specific class, probably with the use of the checkstyle/pmd/findbugs custom rules. (check that a specific method in a specific class has a try catch statement for my runtime exception).

Thanks.

解决方案

There is no existing detector in Checkstyle, FindBugs, or PMD (or their contributing packages) that does what you want. So you will have to roll your own.

The easiest way to solve this without actual programming would be to write a PMD XPath rule which looks for a method X in a class Y and a catch block that catches your runtime exception underneath that.

Failing that, a custom Checkstyle check would be the next easiest, but it requires a small bit of programming and you will have to subsequently deploy your custom check everywhere.

You could also write your own FindBugs detector as suggested in another answer, but since you would not be using any specific FindBugs features (such as byte code analysis), it seems like overkill to me.

这篇关于静态分析自定义规则以强制执行未经检查的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆