2015-04-07 46 views
0

關於我的問題的快速簡要說明:如果我輸入的程序的數據庫中不存在的數字,我希望我的程序能夠在不使程序崩潰的情況下打印出錯誤消息。這裏是我的代碼:如果輸入數據庫中不存在的輸入,如何輸出錯誤消息? N-

listBox1.Items.Clear(); 

    BusinessTier.Business BT = new BusinessTier.Business("netflix.mdf"); 

    if (this.txtMovieID == null) //Hoping this would work and return to the program if I enter a wrong input. 
    { 
    listBox1.Items.Add("**Error, this movie ID doesn't exist, or database is empty?!"); 
    } 

    int N = System.Convert.ToInt32(this.txtMovieID.Text); 
    BusinessTier.Movie movie = BT.GetMovie(N); 

    BusinessTier.MovieDetail movieid = BT.GetMovieDetail(movie.MovieID); //this part will crash the program if I type a number like 0 or greater than 250 when my database contained 250 rows. 


    //display results: 

    listBox1.Items.Add(movie.MovieName); 

    foreach (BusinessTier.Review r in movieid.Reviews) 
    { 
    listBox1.Items.Add(r.UserID + ": " + r.Rating); 
    } 
+0

有什麼'== null'檢查然後...拋出一個異常?我們是否也可以看到「BusinessTier.Business()」方法? –

+0

如果我輸入一個空的輸入,它會拋出一個異常。在BusinessTier.Business()有很多方法,你會喜歡我輸入那些嗎? – CR9191

+0

當你爲不存在的電影調用'BT.GetMovie(N)'時,什麼值最終存儲在「電影」變量中? –

回答

1

第一件事:你仍在處理過程中的剩餘部分,即檢索電影細節,即使this.txtMovieID爲null。你需要停止加工和return

listBox1.Items.Clear(); 

    BusinessTier.Business BT = new BusinessTier.Business("netflix.mdf"); 

    if (this.txtMovieID == null) //Hoping this would work and return to the program if I enter a wrong input. 
    { 
    listBox1.Items.Add("**Error, this movie ID doesn't exist, or database is empty?!"); 
    return; // exit out if the MovieID is null 
    } 

:把支票看到GetMovie(N)結果是否爲空或不是,如果是空,突破和return

int N = System.Convert.ToInt32(this.txtMovieID.Text); 
    BusinessTier.Movie movie = BT.GetMovie(N); 

    if (movie == null) return; // exit if the GetMovie result is null 

    BusinessTier.MovieDetail movieid = BT.GetMovieDetail(movie.MovieID); //this part will crash the program if I type a number like 0 or greater than 250 when my database contained 250 rows. 

    //display results: 

    listBox1.Items.Add(movie.MovieName); 

    foreach (BusinessTier.Review r in movieid.Reviews) 
    { 
     listBox1.Items.Add(r.UserID + ": " + r.Rating); 
    } 
相關問題