【问题标题】:Java Custom Exception handling with Object and Driver class使用 Object 和 Driver 类处理 Java 自定义异常
【发布时间】:2015-04-29 08:45:51
【问题描述】:

我的自定义书籍异常无法与创建书籍对象的程序进行交互,并且最终与我的驱动程序类 Bookstore.java 交互。我的驱动程序类没有发现发生的不一致。喜欢:

  • 标题不能为空或只包含空格
  • isbn 应该是介于 1000 和 10000(含)之间的数字
  • 数量不能为负数(零也可以,表示缺货)

当我运行我的驱动程序类 BookStore.java 时,它没有捕捉到我在 book.java 中编写的上述错误。

------------------------------------创建书籍对象

public class Book{
//instance variables
private String title = "";
private int isbn;
private int quantity;

public Book (String title, int isbn, int quantity)throws BookException{     
//constructors

this.title = title;
this.isbn = isbn;
this.quantity = quantity;

}
public String toString( ){ //toString Method

String s = "";
s = s + "Title: " + this.title + "\nISBN: " + this.isbn
+   "\nQuantity: " + this.quantity + "\n";
return s;

}

public String gettitle( ){
return this.title;
}
public int getisbn( ){
return this.isbn;
}
public int getquantity( ){  
return this.quantity;
}

//mutator methods
public void settitle(String newtitle )throws Exception{
if(newtitle.length()<1){
BookException be = new BookException( );
be.setMessage("Title cannot be blank");
throw be;
}
else{
this.title=newtitle;
}
}

public void setisbn(int newisbn)throws Exception{
if(newisbn>=1000 && newisbn>=10000){
this.isbn = newisbn;
}
else{
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
}

public void setquantity(int newquantity)throws Exception{
if(newquantity>=0){
this.quantity = newquantity;
}
else{
BookException be = new BookException( );
be.setMessage("Quantity can't be a negative number.");
throw be;
}
}

}

-----------------------------------自定义图书例外

public class BookException extends Exception{
//instance variable
private String message = "";

public BookException( ){
//empty constructor

}
public void setMessage(String newMessage){
this.message = newMessage;
}
public String getMessage( ){
return this.message;
}
}

----------------------------------- ------- 驱动类

import java.io.*;
import java.util.*;
public class Bookstore{

//this program will read the information for one book
//it will validate it and print it if correct

public static void main(String arg[ ]) throws Exception{

Scanner sc = new Scanner(System.in);
int size = 3;
int isbn=0;
int quantity = 0;
String title = "";
int count=0;
boolean exit = false;
Book oneBook;

try{
System.out.print("Enter title: ");
title = sc.nextLine( );
sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
sc = new Scanner(System.in);
System.out.println();
oneBook = new Book(title, isbn, quantity); //attempting to create the book
//if any information about the book is inconsistent the BookExcpetion will be
//thrown by the Book constructor/set methods and it should be caught
System.out.println("The book entered was:");
System.out.println(oneBook.toString( ));
}

catch(InputMismatchException ime){
System.out.println("you did not enter a number");
}
catch (BookException be){
System.out.println(be.getMessage( )); //calling the getMessage from BookException.java
}

} //main method
} //class

非常感谢您的帮助和提示!

【问题讨论】:

    标签: java object exception exception-handling driver


    【解决方案1】:

    你的构造函数总是通过。变化自

    this.title = title;
    this.isbn = isbn;
    this.quantity = quantity;
    

    setTitle(title);
    setIsbn(isbn);
    setQuantity(quantity);
    

    【讨论】:

      【解决方案2】:
      public Book (String title, int isbn, int quantity)throws BookException{     
      //constructors
      
      this.title = title;
      this.isbn = isbn;
      this.quantity = quantity;
      
      }
      

      只是在那里添加一个 throws 子句,不会这样。你也需要真正扔掉它们。例如,如果 title 不能为 null 或为空:

      public Book (String title, int isbn, int quantity)throws BookException{     
      //constructors
      
      this.title = title;
      if ( title == null || title.isEmpty())
        throw new BookException("Please provide a title");
      this.isbn = isbn;
      this.quantity = quantity;
      
      }
      

      【讨论】:

      • 嗯,我理解你的方法。但我也有:catch (BookException be){ System.out.println(be.getMessage());在我的司机课上。从 BookException.java 调用 getMessage :(
      • Asia_x3 : 是的,但是只要不抛出异常,是无法捕获的。
      【解决方案3】:

      Murat.K 已经提供了一个answer,我不再赘述。

      不过,我将提供一些额外的建议。首先,Java 已经有一个处理非法/无效参数的异常,称为IllegalArgumentException。您应该真正使用它,而不是创建自己应该做同样事情的异常。另外,请注意IllegalArgumentExceptionunchecked exception,这意味着您不需要在方法签名或catch 块中使用throws IllegalArgumentException(除非您想捕获它)。

      如果您仍想使用自己的异常,则不需要 message 字段及其 setter 和 getter,因为父类 Exception 已经拥有它们(好吧,除了 setter,但不需要,因为无论如何您在构造函数中设置了消息)。所以你的班级应该是这样的

      public BookException extends Exception {
          public BookException(String message) {
              super(message);
          }
      }
      

      你可以像这样把它放在一行上

      throw new BookException("some error"); //no need for setter
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-11
        • 2015-07-01
        相关资源
        最近更新 更多