Java 未处理的异常编译错误:ClassNotFoundException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22367323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unhandled exception compile error: ClassNotFoundException
提问by dtg
I know this is a common question, but despite adding mysql-connector
to my library in IntelliJ IDEA, the IDE still can't seem to locate the class. As you can see in the screenshots below, I have added the mysql-connector
jar as a library for my project, yet it doesn't seem to see that it is present:
我知道这是一个常见问题,但是尽管mysql-connector
在 IntelliJ IDEA 中添加到我的库中,IDE 似乎仍然无法找到该类。正如您在下面的屏幕截图中看到的,我已将mysql-connector
jar添加为我的项目的库,但它似乎没有看到它存在:
I haven't been able to find a solution other than 'add the library to the project'. It seems as though there is a missing step somewhere...
除了“将库添加到项目”之外,我找不到其他解决方案。好像在某处遗漏了一步……
采纳答案by Steinar
You will also need to add the library as a dependency to the module that needs it.
您还需要将该库添加为需要它的模块的依赖项。
Choose Project Settings > Modules
. Select the Module that needs the library (in your case it seems like you have only one module in your project, ChatBot
). Select the Dependencies
tab. Click the '+' button and choose Library...
). Finally, select the mysql-connector..
library that you added to the project.
选择Project Settings > Modules
。选择需要库的模块(在您的情况下,您的项目中似乎只有一个模块,ChatBot
)。选择Dependencies
选项卡。单击“+”按钮并选择Library...
)。最后,选择mysql-connector..
您添加到项目中的库。
Edit: I see now that this wasn't your problem at all. The problem with your code is that you have an unhandled exception from Class.forName()
. The method can throw the checked exception: ClassNotFoundException
, which must be handled by adding a catch
or by adding throws ClassNotFoundException
to the method signature of getConnection()
.
编辑:我现在明白这根本不是你的问题。您的代码的问题在于您有一个未处理的异常Class.forName()
. 该方法可以抛出已检查的异常:ClassNotFoundException
,必须通过添加 acatch
或添加throws ClassNotFoundException
到 的方法签名来处理getConnection()
。
In such cases with error in the code, the easiest way to figure out what's wrong to simply move the caret to the code with the red squigly line and see what IDEA says in the bottom status bar. Alternatively you can hover the mouse pointer above it and the error message is presented as a popup.
在这种代码错误的情况下,找出问题的最简单方法是将插入符号移动到带有红色波浪线的代码上,然后查看 IDEA 在底部状态栏中的内容。或者,您可以将鼠标指针悬停在其上方,错误消息将显示为弹出窗口。
回答by dtg
I needed to change the exception type from SQLException
in the corresponding catch
block where the mysql-connector
was being loaded to the base type Exception
. That seems to have cleared up the problem.
我需要将异常类型从正在加载SQLException
的相应catch
块中mysql-connector
更改为基本类型Exception
。这似乎解决了问题。