Dietel 11.19如何添加前后条件

时间:2015-10-28 17:20:00

标签: java

编写一个程序,显示一个构造函数,将有关构造函数失败的信息传递给异常处理程序。定义类SomeClass,它在构造函数中抛出异常。你的程序应该尝试创建一个SomeClass类型的对象,并捕获从构造函数抛出的异常。

如何为此代码添加前置和后置条件?

import java.util.Scanner;

public class Demo3 {


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

    SomeClass testException;

    try
    {
        testException = new SomeClass();
    }
    catch(Exception e)
    {
        System.out.println();
    }
}
}

public class SomeClass{


  public SomeClass () throws Error { 
    throw new Exception();

  } 
}

2 个答案:

答案 0 :(得分:0)

你应该能够创建一个构造函数,它接受两个参数并在那里抛出异常。此外,如果要验证某些值,可以以编程方式断言某些前置条件和后置条件。我希望它有所帮助。您的代码可能如下所示:

public class Demo3 {
  public static void main(String[] args){

  Scanner scan=new Scanner(System.in);

  System.out.println("Enter the firstNumber:");

  int a=scan.nextInt();

  System.out.println("Enter the secondNumber:");

  int b=scan.nextInt();

 //you can write some assertion here to meet the pre-conditions
assert(b>0):"You cannot enter a number less or equal to zero";

 SomeClass testException;

 try
 {
    testException = new SomeClass(a,b);
 }
 catch(Exception e)
   {
    System.out.println("Exception occurred:"+e.getMessage());
   }
 }
 }

public class SomeClass{
  int firstNumber;
  int secondNumber;
  public SomeClass () {

  } 
  public SomeClass (int firstName,int secondName) throws Exception { 
    //the message to show when you have getMessage() invoked
    throw new Exception("Some exception occurrred");

  } 
}

答案 1 :(得分:0)

这确实有帮助,谢谢!我已经重写了我的代码,但我不明白如何在不符合条件的前后条件时抛出异常。

如果不满足前置条件,如何抛出异常,例如InputMismatchException?

import java.util.Scanner;

public class Demo3 {
  public static void main(String[] args){

  Scanner scan=new Scanner(System.in);

  System.out.println("Enter a number between 0 and 10:");

  int a=scan.nextInt();

  System.out.println("Enter another number between 0 and 10:");

  int b=scan.nextInt();

 //assertion here to meet the pre-conditions
  assert (a >= 0 && a <= 10) : "bad number: " + a;
  assert (b >= 0 && b <= 10) : "bad number: " + b;

 SomeClass testException;

 try
 {
    testException = new SomeClass(a,b);
 }
 catch(Exception e)
   {
    System.out.println("Exception occurred: "+e.getMessage());
   }

 }
 }

public class SomeClass{
  int a;
  int b;
  public SomeClass () {

  } 
  public SomeClass (int a,int b) throws Exception { 

    throw new Exception("You've got an error!");

  } 
}