java - 如何在这段代码中使用 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,请帮我在这段代码中添加它们,以便我能理解更多。
解决方案
请试试这个,我希望这能帮助你摆脱困境。
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());
}
}
推荐阅读
- reactjs - 在功能组件的返回中使用异步
- java - 弹性搜索在 Spring Boot 中使用列表参数进行查询
- javascript - 上传文件并显示其内容
- c - 在我使用 free() 函数和 Null 指针之后......程序仍然崩溃
- flutter - 即使在使用 Firebase.Initialize 方法之后,我得到的错误是 No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
- r - 将 ifelse 应用于多个列并创建新列
- javascript - Javascript对象方法在调用时不起作用
- linux - 根据标题拆分fasta文件
- javascript - node_modules/ng2-bs3-modal/components/modal-header.d.ts.ModalHeaderComponent.html(3,107) 中的错误:属性“modal”是私有的,只能访问
- excel - VBA 在 TOR 中打开链接(每个都在新选项卡中)