异常体系
异常指的是程序运行过程中出现不正常的情况,会导致程序的运行中断
1、异常体系结构图
两大类:
1.1错误
1.2异常
1.2.1检查时异常
程序编译的时候,会对现有的代码做检查
1.2.2运行时异常
2、异常的分类
3、异常的处理机制
try catch作用就是发现异常并且处理异常。
try(){
}catch(){
日志:ex.printStackTrace();
}
变量的作用域:
提升变量作用域
try {
int i = input.nextInt();
System.out.println(i/0);
} catch (Exception e) {
e.printStackTrace();
}
int只能在try里面访问,提升作用域如下
int i = 0;
try {
i = input.nextInt();
System.out.println(i/0);
} catch (Exception e) {
e.printStackTrace();
}
提升作用域
4、异常的关键字
try
catch
finally程序在运行过程中,是否发生异常都会执行到的模块
public void avg () throws Exception
throws Exception:声明一个异常
5、声明异常
throws Exception:声明一个异常
//日期转字符串
Date date = new Date();//当前日期+时间
SimleDateFormat sdf =new SimleDateFormat("yyy-MM-dd HH:mm:ss")
//格式化日期的工具类
//sdf对象的format
String dt = sdf.format(date)
//字符串转日期
String s1 = "2300-8-9 21:30:50";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//调用对象
Date date = null;//提升作用域
try {
date = simpleDateFormat.parse(s1);//调用方法
} catch (ParseException e) {//解决异常
}
System.out.println(date);