0

I am trying to write a custom exception class for a program that connects to a local MySQL database and throws an exception if we are unable to connect (bad database, username, or password).

However my professor put a weird requirement in for my custom exception class: "Provide a constructor that accepts a parameter of type Exception and additional error strings". I have never touched an exception class that takes a parameter of type Exception before... this seems very odd.

My exception constructor:

public DLException(Exception e, String... errMsgs){
    for(int i = 0; errMsgs.length > i; i++){
        System.out.println(errMsgs[i]);
    }
}

My database connect() function:

this.connection = DriverManager.getConnection(Uri, Username, Password);
if(this.conn != null){
    return true;
} else {
    customException ce = new Exception();
    throw new customException(ce, "Connection Failure: bad creds");
}

code that catches my exception:

try{
    this.connect();

    this.close();
} catch(customException ce){
    ce.printStackTrace();
} catch (SQLException sqle){
    sqle.printStackTrace();
} catch(Exception e){
    e.printStackTrace();
}

What is the proper way to be throwing this exception and inputting an Exception parameter with it??? And what would I want to do with the Exception object inside my constructor? Unfortunately I'm still slightly new to using them.

Ryan
  • 262
  • 3
  • 19
  • See [`Exception​(String message, Throwable cause)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Exception.html#%3Cinit%3E(java.lang.String,java.lang.Throwable)) and [`Throwable.getCause()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#getCause()). – Jai Feb 20 '19 at 03:22
  • This is not how you create a custom exception and your own class should extend Exception and your constructor should call the super's constructor first line, passing in the String of interest. Please see the duplicate for an example. – Hovercraft Full Of Eels Feb 20 '19 at 03:24

0 Answers0