首页 > 解决方案 > 如何在这段代码中使用 try 和 catch (java)

问题描述

package zed;

import java.util.Stack;

public class decTobin {
    public void convertBinary(int num) {
        Stack<Integer> stack = new Stack<Integer>();
        while (num != 0) {
            int d = num % 2;
            stack.push(d);
            num /= 2;
        }

        while (!(stack.isEmpty())) {
            System.out.print(stack.pop());
        }
    }

    public static void main(String[] args) {
        int decimalNumber = 123;
        System.out.print("binary of " + decimalNumber + " is :");
        new decTobin().convertBinary(decimalNumber);
    }
 }

-

我不明白 java 中的 try 和 catch,请帮我在这段代码中添加它们,以便我能理解更多。

标签: java

解决方案


请试试这个,我希望这能帮助你摆脱困境。

while (num != 0) {

try { // checks code for exceptions
        int d = num % 2;

            stack.push(d);

            num /= 2

        break; // if no exceptions breaks out of loop
    } 
    catch (Exception e) { // if an exception appears prints message below
        System.err.println("Please enter a number! " + e.getMessage());
        continue; // continues to loop if exception is found
    }

 }

或者您可以捕获如下异常

public static void main(String[] args) {

        int decimalNumber = 123;

        System.out.print("binary of " + decimalNumber + " is :");
 try { // checks code for exceptions
        new decTobin().convertBinary(decimalNumber);

  } 
        catch (Exception e) { // if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
}
    }

推荐阅读