java异常处理练习题
时间: 2023-11-09 08:09:12 浏览: 42
好的,以下是一些Java异常处理练习题:
1. 编写一个程序,在控制台上输出 1 到 10 的数字,但是当数字为 5 时,抛出一个自定义异常,程序继续执行直到输出完毕。
```java
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
try {
if (i == 5) {
throw new CustomException("数字为5,抛出自定义异常");
}
System.out.println(i);
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
}
```
2. 编写一个程序,模拟用户登录过程。如果用户名和密码不匹配,或者用户名不存在,抛出一个自定义异常,并输出错误信息。如果用户名和密码匹配,则输出登录成功。
```java
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
String username = "admin";
String password = "123456";
String inputUsername = "admin";
String inputPassword = "123456";
try {
if (!inputUsername.equals(username)) {
throw new CustomException("用户名不存在");
}
if (!inputPassword.equals(password)) {
throw new CustomException("密码不正确");
}
System.out.println("登录成功");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
```
3. 编写一个程序,从控制台输入一个整数 n,计算阶乘 n!。如果输入的不是整数,或者 n 小于 0,抛出一个自定义异常,并输出错误信息。
```java
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = 0;
try {
System.out.print("请输入一个整数:");
n = scanner.nextInt();
if (n < 0) {
throw new CustomException("输入的数必须大于等于0");
}
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "! = " + result);
} catch (InputMismatchException e) {
System.out.println("输入的不是整数");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
```