try-catch
try-catch捕获try代码块的异常,并在catch中执行,try外面的代码块,会继续执行
如下所示
package newT.exception;
import java.util.Scanner;
/**
* try-catch处理可能会出现异常情况,若发生在try中发现异常,在catch处理以后,try-catch外层的语句还能继续执行
*/
public class TryCatch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("---------学生信息录入---------------");
String name = ""; // 获取学生姓名
int age = 0; // 获取学生年龄
String sex = ""; // 获取学生性别
try {
System.out.println("请输入学生姓名:");
name = scanner.next();
System.out.println("请输入学生年龄:");
age = scanner.nextInt();
System.out.println("请输入学生性别:");
sex = scanner.next();
} catch (Exception e) {
e.printStackTrace();
System.out.println("输入有误!");
}
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
System.out.println("性别" + sex);
}
}
throw
throw捕获异常后不会执行try代码块以外的代码
package newT.exception;
public class Throw {
public static void main(String[] args) {
try {
throwMethods("2.123za");
System.out.println("不会执行");
} catch (Exception e) {
System.out.println("交给外层处理");
e.printStackTrace();
}
}
public static void throwMethods(String data) throws Exception {
try {
Double.parseDouble(data);
} catch (NumberFormatException e) {
throw new Exception("发送异常");
}
System.out.println("throw捕获异常后不会执行后面的代码");
}
}
throws
throws捕获异常后不会执行try代码块以外的代码
package newT.exception;
import java.io.File;
import java.io.FileInputStream;
/**
* throws 向外抛异常 抛给调用者
* 如果没有try-catch则一层一层往上抛
* 有try-catch则捕获抛出的异常对其进行处理
*/
public class Throws {
public static void main(String[] args) throws Exception {
try {
//调用者
throwException();
} catch (Exception e){
System.out.println(e.getMessage());
}
}
public static void throwException() throws Exception{
File file = new File("404");
FileInputStream fileInputStream = new FileInputStream(file);
System.out.println("代码不会继续执行");
}
}