Java Throwing exception with parameters (Exception e, String... errs)

56 Views Asked by At

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.

0

There are 0 best solutions below