如何在python中捕获涉及太多参数的错误?

时间:2016-10-30 03:34:52

标签: python

我正在尝试准备能够捕获用户输入的命令中的错误并返回建议的代码。

例如,如果我输入turnleft(2,1)并且实际命令是turnLeft(2,1),程序将返回:“哦不!你键入:turnleft(2,1)。你的意思是键入turnLeft吗?“

到目前为止,如果错误发生在括号之前,程序会捕获我需要的所有错误。但是现在我正在尝试编写能够捕获太多参数的代码。例如,turnLeft(3,2,1)将返回,“看起来你在函数中输入了太多参数。试试turnLeft(2,1)。

我该怎么做?

目前程序只是回复:“哦不!你键入:turnLeft(3,2,1)。你的意思是turnLeft吗?“但我希望它能回复一条消息,说有太多的争论。如何捕获括号内的错误而不是括号外的错误?

到目前为止,这是我的代码:

public class ImplementDatabase 
{
    private String user;    // MySQL user account 
    private String pass;    // MySQL account password
    private String host;    // MySQL host     
    Connection conn;        // application needs to communicate with JDBC driver
    Statement st;           // issuing commands against the connection is reqiured
    Scanner keyboard;       // get input from user

    /* When instantiated the JDBC driver attempts to load */
    public ImplementDatabase()
    {
        try
        {
            Class.forName ("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException e)
        {
            System.out.println("Could not load the driver");
        }
    }

    public void createDatabase() 
    {
        try 
        {   
            this.readLogin();
            // prompts user to enter login info to console
            this.conn = DriverManager.getConnection
            ("jdbc:mysql://"+host+":3306", user, pass);
            this.st = this.conn.createStatement();
            int Result = this.st.executeUpdate("CREATE DATABASE ChessLeague");
            System.out.println("You are successfully connected to the "
                    + "Chess League Database");
        } 

        catch (SQLException ex)
        {
            Logger.getLogger(ImplementDatabase.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Please check that the login information you"
                    + "have provided is correct");
        }
    }


    public void createPlayerTable()
    {
        try 
        {
            this.st = this.conn.createStatement();
            this.st.executeUpdate("CREATE TABLE IF NOT EXISTS PLAYER"
                    + "(PlayerName VARCHAR(30)PRIMARY KEY,"
                    + "DateOfBirth DATE,"
                    + "FIDERating tinyint,"
                    + "ClubName FOREIGN KEY fk_club(Clubname) REFERENCES club(ClubName)");                    
                    // Create Actor table
        } 
        catch (SQLException ex) 
        {
            Logger.getLogger(ImplementDatabase.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }

    private void readLogin()
    {
        this.keyboard = new Scanner(System.in);
        System.out.println("Please enter username:");
        this.user = keyboard.next();
        System.out.println("\nPlease enter password:");
        this.pass = keyboard.next();
        System.out.println("\nPlease enter host or ip address:");  
        this.host = keyboard.next();
    }
}

0 个答案:

没有答案