Java Error Handling - Is this the best way to do this?

时间:2015-12-08 19:24:36

标签: java error-handling

I have an error in a console program I'm making, in which I can't seem to handle an error.

If a user enters an incorrect input type (such as an float where an int goes), they are reprimanded, and the program functions (even though the program shuts down, it does it my way):

// MARK: At UICollectionViewCustomLayout:

public override init() {
    super.init()
    // Register the NIB of the view that will hold the shadows:
    let nib = UINib(nibName: "Shadow", bundle: nil)
    self.registerNib(nib, forDecorationViewOfKind: "shadow")
}

public override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
    let layoutAtt: UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes(forDecorationViewOfKind: "shadow", withIndexPath: indexPath)
    layoutAtt.frame = (layoutAttributesForItemAtIndexPath(indexPath)?.frame)!
    layoutAtt.zIndex = -1
    return layoutAtt
    }

public override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var atts = [UICollectionViewLayoutAttributes]()
    let numberOfItems:Int = (self.collectionView?.numberOfItemsInSection(0))!
    for index in 0..<numberOfItems {
        let layoutItem = layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0))!
        let frameItem = layoutItem.frame
        if CGRectIntersectsRect(frameItem, rect) {
            atts.append(layoutAttributesForDecorationViewOfKind("shadow", atIndexPath: NSIndexPath(forItem: index, inSection: 0))!)
            atts.append(layoutItem)
        }
    }
    return atts
}

// MARK: At the Nib Class File:

// Here I created a additional view to append the shadow. 
// Thats because awakeFromNib() is called before the UICollectionViewCustomLayout 
// have a chance to layout it, but I want to make 
// use of shadowPath to gain performance, thats why 
// I make use of the additional UIView with autolayout stuffs.

@IBOutlet weak var shadowView: UIView!

override func awakeFromNib() {
    super.awakeFromNib()
    shadowView.layer.shadowOffset = CGSizeMake(0, 0)
    shadowView.layer.shadowColor = UIColor.yellowColor().CGColor
    shadowView.layer.shadowRadius = 3
    shadowView.layer.shadowOpacity = 1
    let shadowFrame: CGRect = shadowView.layer.bounds
    let shadowPath: CGPathRef = UIBezierPath(rect: shadowFrame).CGPath
    shadowView.layer.shadowPath = shadowPath
    shadowView.clipsToBounds = false
    self.clipsToBounds = false
}

If a user enters, for example, a zero as a variable that cannot equal zero (due to division of zero), the user is reprimanded, and life still goes on, and the program still functions:

while(!scanner.hasNextLong()){
                System.out.println("You entered something bad..  Why do you hurt me?");
                System.out.println("*Calcumatastic dies, and I hope you feel remorseful*");
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException f) {
                    f.printStackTrace();
                }
                System.exit(0);
            }

However, if a user attempts to divide by zero, THEN enters an incorrect input type, the program crashes. What am I doing wrong? I've tried entering a try/catch- while loop as I did in other instances, but it doesn't seem to do the trick:

while (b == 0) {
            System.out.println("Did you even read the instructions??  You cannot divide by zero!");
            System.out.println();
            System.out.println("Second Integer: ");
            b = scanner.nextLong();
        }

2 个答案:

答案 0 :(得分:0)

如果您尝试按零执行除法,则会抛出java.lang.ArithmeticException,当您尝试读取长整数并且用户输入无法解析的内容时,会抛出InputMismatchException(可能你称之为&#34;崩溃&#34;)。

发生错误是因为您在用户输入0时使用b = scanner.nextLong();而未检查用户是否输入了有效的长值。

以下是您调整的代码:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    long b = 0;

    do {
        System.out.println("Second Integer: ");

        b = readLong(scanner);

        if (b == 0) {
            System.out.println("Did you even read the instructions??  You cannot divide by zero!");
            System.out.println();
        }
    } while (b == 0);
}

private static long readLong(Scanner scanner) {
    if (!scanner.hasNextLong()) {
        System.out.println("You entered something bad..  Why do you hurt me?");
        System.out.println("*Calcumatastic dies, and I hope you feel remorseful*");
        try {
            Thread.sleep(4000);
        } catch (InterruptedException f) {
            f.printStackTrace();
        }
        System.exit(0);
    }
    return scanner.nextLong();
}

答案 1 :(得分:0)

您的问题是您的输入验证似乎是连续的。也就是说,检查无效输入,然后检查零值。你可能想在每次输入时都这样做。

您可能希望在单个循环中检查所有错误情况。类似的东西:

System.out.println("Second Integer: ");
// a loop wrapping your other validation checks
while(scanner.hasNext()){ // while there is input:
    while(!scanner.hasNextLong()){ // check for non-long input
        System.out.println("You entered something bad..  Why do you hurt me?");
        System.out.println("*Calcumatastic dies, and I hope you feel remorseful*");
        try {
            Thread.sleep(4000);
        } catch (InterruptedException f) {
            f.printStackTrace();
        }
        System.exit(0);
    }
    b = scanner.nextLong();
    while (b == 0) { // check for non-zero input
        System.out.println("Did you even read the instructions??  You cannot divide by zero!");
        System.out.println();
        System.out.println("Second Integer: ");
        b = scanner.nextLong();
    }
}