您的位置:首页 > 编程语言 > Java开发

Java的异常处理:try-catch-finally throws throw

2017-05-27 09:31 671 查看

Java的异常分为

编译时异常:这类异常在编写时就会出错,必须处理,不然没法编译

public void method() {
//此处会弹出编译时异常:FileNotFoundException
FileInputStream stream = new FileInputStream("Hello.txt");

int b;
//此处会弹出编译时异常:IOException
if ((b = stream.read()) != -1) {
System.out.println((char)b);
}
//此处会弹出编译时异常:IOException
stream.close();
}


运行时异常:这类异常编写时是正常的,运行时才会出错

public static void method1() {
int[] arr = new int[10];
//此处异常编写时并不会弹出错误,运行时弹出异常:ArrayIndexOutOfBoundsException
System.out.println(arr[10]);
}


try-catch-finally:具体处理异常的过程

throws:把异常抛给调用该方法的对象来处理

public void method2() {
//method2方法收到异常后,进行了具体的处理
try {
method();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("异常处理完成!");
}
}

//method方法使用throws把异常交给调用该方法的对象处理
public void method() throws FileNotFoundException, IOException{
FileInputStream stream = new FileInputStream("Hello.txt");

int b;
if ((b = stream.read()) != -1) {
System.out.println((char)b);
}
stream.close();
}


throw:手动抛出一个异常

public void method4() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学生成绩:");
double score = scanner.nextDouble();

if (score >= 0 && score <= 100) {
System.out.println(score);
} else {
//throw手动抛出一个RuntimeException,此处建议使用运行时异常类
throw new RuntimeException("您输入的成绩有误");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐