java异常处理练习题
时间: 2023-09-08 08:15:08 浏览: 60
1. 编写一个程序,从控制台读取一个整数,然后输出这个整数的平方值。如果输入的不是整数,则输出错误信息。
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int num = scanner.nextInt();
System.out.println(num * num);
} catch (Exception e) {
System.out.println("输入错误,请输入一个整数!");
}
}
}
```
2. 编写一个程序,从控制台读取两个整数,然后输出它们的商。如果除数为0,则输出错误信息。
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
if (num2 == 0) {
throw new ArithmeticException("除数不能为0!");
}
System.out.println(num1 / num2);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("输入错误,请输入两个整数!");
}
}
}
```
3. 编写一个程序,从控制台读取一个字符串,然后将字符串转换为整数并输出。如果字符串不能转换为整数,则输出错误信息。
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
String str = scanner.nextLine();
int num = Integer.parseInt(str);
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("输入错误,请输入一个整数字符串!");
} catch (Exception e) {
System.out.println("程序发生异常:" + e.getMessage());
}
}
}
```
4. 编写一个程序,从控制台读取一个字符串,然后判断字符串是否是一个合法的邮箱地址。如果是合法的邮箱地址,则输出“合法的邮箱地址”,否则输出“非法的邮箱地址”。
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
String email = scanner.nextLine();
if (email.matches("^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
System.out.println("合法的邮箱地址");
} else {
System.out.println("非法的邮箱地址");
}
} catch (Exception e) {
System.out.println("程序发生异常:" + e.getMessage());
}
}
}
```
5. 编写一个程序,从控制台读取一个文件路径,然后读取文件内容并输出。如果文件不存在,则输出错误信息。
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
String filePath = scanner.nextLine();
File file = new File(filePath);
if (!file.exists()) {
throw new Exception("文件不存在!");
}
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
```