2016-05-17 77 views
-1

我想要做的是给2至60之间的数字。如果数字不包括在这个“空间”,那么将有一个例外,名称InvalidLicenceNumberException。我有和类UserInput,但它并不需要上传其确定 我的主:例外如何使用,如果在尝试赶上

import java.io.*; 
public class Exercv { 
    public static void main(String[] args) { 
     int ArTh ; 
     ArTh=Vehicle.NumberPos(); 
     try { 
      if(ArTh<2 || ArTh>60){ 
       ArThEx(); 
      } 
     } catch(InvalidLicenceNumberException e){ 
      System.out.println(""+e); 
      throw new InvalidLicenceNumberException ("There is an exception!"); 
     } 
    }   

我的类车辆:

public abstract class Vehicle { 
static int user; //for userinput 
    public static int ArTh() { 
     System.out.println("Give number between 2 until 60"); 
     user=UserInput.getInteger(); 
     if(user>=2 && user<=60){ 
      System.out.println(" Possition is : "+ user); 
     } 
     return user; 
    } 

    public static void ArThEx() throws ArithmeticException{ 
     System.err.println("There is an exception"); 
     System.err.println("Positions arent acceptable"); 
    } 
    } 

我的特例:

import java.lang.Exception; 

public class InvalidLicenceNumberExceptio extends MyException { 
    public InvalidLicenceNumberExceptio(String s){ 
     super(s); 
    } 
} 
+0

请格式化您的代码。 – SomeJavaGuy

+0

是的,我看到我没有做得很好对不起。我会 –

+0

这可能是有联系的,并且很有用:[我如何创建一个异常,以遏制int范围等...](http://stackoverflow.com/questions/15468418/how-can-i-create-an-exception-that-c​​hecks-for-int-range-number-type-and-not-a) –

回答

0

你可以直接把你的例外,是这样的:

if (user < 2 || user > 60) { 
     throw new InvalidLicenceNumberException("Your number needs to be between 2 and 60"); 
     System.exit(1); 
    } 

或者在你的ArThEx功能,这是通常的封装它这是一个更好的做法。

public static void ArThEx() throws InvalidLicenceNumberException { 
    throw new InvalidLicenceNumberException("Your number needs to be between 2 and 60 (you typed " + user + ")"); 
    System.exit(1); 
} 
+0

有两种不同的选择?如果是,在方法的第二选择上,我会在主要上写什么? –

+0

确实有两种不同的选择。首先,我会直接将它放入“Vehicle”类。第二,是的,我会把它放在你的'main'函数中,直接检查你的范围。 –

0

你可能想要类似下面的代码。

请注意,从主方法重新抛出异常是没有意义的,因为无论如何什么都不会收到。 所以只打印您的消息,让程序结束(可能迫使与System.exit退出代码)

public static void ArThEx() throws InvalidLicenceNumberException{ 

    System.err.println("There is an exception"); 
    System.err.println("Positions arent acceptable"); 
    throw new InvalidLicenceNumberException("Out of range"); 
} 
+0

如果我明白要删除我在类上创建的方法车辆ArThEx?也可以取代你在我的主要上写的东西吗? –

+0

如果此方法的目的仅仅是打印事件并抛出异常,它不必位于'Vehicle'类中。这可能是你的主要课程的一种方法。 – Berger

0

试图改变自己的ArThEx方法,这样,让我知道,如果它

public static void ArThEx() throws ArithmeticException{ 
     System.err.println("There is an exception"); 
     System.err.println("Positions arent acceptable"); 
     throw new InvalidLicenceNumberExceptio(); 
    }