Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled exception compile error: ClassNotFoundException

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:

enter image description here

enter image description here

enter image description here

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...

like image 398
dtg Avatar asked Mar 13 '14 01:03

dtg


People also ask

Why do we get ClassNotFoundException in Java?

ClassNotFoundException is a checked exception in Java that occurs when the JVM tries to load a particular class but does not find it in the classpath.

How to catch ClassNotFoundException in Java?

ClassNotFoundException is a checked exception, so it has to be catch or thrown to the caller. ClassNotFoundException always occurs at runtime because we are indirectly loading the class using Classloader. Java compiler has no way to know if the class will be present in the classpath at runtime or not.

What is unhandled exception type?

An unhandled exception occurs when the application code does not properly handle exceptions. For example, When you try to open a file on disk, it is a common problem for the file to not exist. The . NET Framework will then throw a FileNotFoundException.

Why I am getting NoClassDefFoundError?

The NoClassDefFoundError is a runtime error in Java that occurs if the Java Virtual Machine (JVM) or a ClassLoader instance attempts to load the definition of a class that could not be found. The class definition exists at compile-time but is not available at runtime.


1 Answers

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.

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().

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.

like image 196
Steinar Avatar answered Oct 16 '22 17:10

Steinar