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.

2
  • See Exception​(String message, Throwable cause) and Throwable.getCause(). Commented Feb 20, 2019 at 3: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. Commented Feb 20, 2019 at 3:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.