Java 自定义异常、手动抛出异常

平平无奇的一块板砖 2019-09-17 08:35:47
在程序中要求输入y/n,如果输入其他字符则抛出自定义错误,但是一旦抛出错误程序就会停止运行,如何让程序返回输入时的状态,重新输入?

package test;

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Test {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String str = input.next();
if("y".equals(str)||"n".equals(str)){
System.out.println(str);
}else{
throw new Exception("输入异常");
}
}
}

...全文
443 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 2 楼 Shcm@313 的回复:
[quote=引用 1 楼 淡青の月的回复:]public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String str = null;
System.out.println("请输入(y/n)");
while (true) {
try {
str = input.nextLine();
if("y".equals(str)||"n".equals(str){
System.out.println(str);
break;
}else{
throw new Exception("Exception");
}
} catch (Exception e) {
System.out.println("输入有误");
System.out.println("请重新输入..");
}
}
}

可不可以帮忙解释一下,为什么while里面要放true,还有else里那句话是干什么用的[/quote]
这里true是作为一个无限循环 else里面就是你抛出的异常呢。他用一个catch 就是异常手动处理 会执行里面的语句 直到break该次循环 会停止。
  • 打赏
  • 举报
回复
引用 1 楼 淡青の月的回复:
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String str = null;
System.out.println("请输入(y/n)");
while (true) {
try {
str = input.nextLine();
if("y".equals(str)||"n".equals(str){
System.out.println(str);
break;
}else{
throw new Exception("Exception");
}
} catch (Exception e) {
System.out.println("输入有误");
System.out.println("请重新输入..");
}
}
}
可不可以帮忙解释一下,为什么while里面要放true,还有else里那句话是干什么用的
淡青の月 2019-09-17
  • 打赏
  • 举报
回复
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String str = null;
System.out.println("请输入(y/n)");
while (true) {
try {
str = input.nextLine();
if("y".equals(str)||"n".equals(str){
System.out.println(str);
break;
}else{
throw new Exception("Exception");
}
} catch (Exception e) {
System.out.println("输入有误");
System.out.println("请重新输入..");
}
}
}
BoringRong 2019-09-17
  • 打赏
  • 举报
回复
在java中的异常为阻断式异常,抛出异常的目的是为了打断程序的运行,阻止在错误的情况下继续执行的

51,411

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧