1

I am getting a ClassNotFoundException when I attempt to define a driver for a SQLServer database in java code.

Image of code and error message.

Can anyone clarify why this might be, I've seen similar questions but none of their answers seem to work.

Thanks.

Community
  • 1
  • 1
eocsap
  • 92
  • 10
  • 1
    Eclipse already shows the possible fixes, it's *possible* that `Class.forName` throws an exception (if the class cannot be located) hence you need to throw or catch it. – Mark Dec 05 '18 at 14:14

2 Answers2

1

That is a compilation error.

When you call Class.forName() the method may throw the checked exception ClassNotFoundException. Since it is a checked exception your code must either handle it in the current method, or declare it in the method's throws clause.

I suggest that you read the Java tutorial's lesson on exceptions and exception handling, or the Q&A that I have marked this as a dup of.

Note that if this exception actually occurs when your application is run, it means that the Class.forName was unable to load the JDBC driver class that you named. This typically means that the JAR containing the driver class is not on the runtime classpath. Unless your application can proceed without talking to the database at all(!), this is an exception that it won't be able to recover from.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks for the clarification on this. By the way, could this explain why eventually I get a ServletException error saying "non http request or response" when I attempt to use the servlet? (I'm clutching at straws with this one, I know) – eocsap Dec 05 '18 at 15:24
  • I doubt it. See this Q&A - https://stackoverflow.com/questions/5117121/javax-servlet-servletexception-non-http-request-or-response-in-jboss. If you get stuck, you could ask a new Question: include the full stacktrace and relevant code. – Stephen C Dec 05 '18 at 22:45
0

So basically the screenshot says that you have to catch ClassNotFoundException:

try {
   Class.forName("...");
} catch (ClassNotFoundException e) {
   // log exception here
}

or re-throw it in your method signature

void doSmth() throws ClassNotFoundexception {
    ...
    Class.forName("...");
    ...
}
Dzmitry Bahdanovich
  • 1,735
  • 2
  • 17
  • 34