程序运行—>异常—>程序中断
程序中的异常
- 最容易发生异常的情况:和用户的交互;
异常处理机制
- try
释放可能会异常的所有代码 - catch
当出现异常时捕获异常 可以多个叠加 从小到大 - finall
无论是否异常,代码总能执行 一定会执行;即将要return但是还没有return的时候 - throw
申明方法时可能要抛出异常 显示抛出异常 异常肯定会发生; - throws
手动抛出异常 用在方法方法申明的时候,可能会抛出多个异常;
exception异常 所有异常的父类
RunTimeException - ArithrmeticException 算术异常
- 索引越界异常
- 空指针异常
- 方法接收非法参数异常
- 加载类错误异常
- 对象强制类型转换出错;
- 数据格式化异常;
多重catch块
- 由小到大
- try catch可嵌套,不可交叉,try和catch必须匹配;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入被除数:");
try {
//放可能会引发异常的代码;
//不引发异常的代码不鼓励 里放入;
int n = scanner.nextInt();
System.out.println("请输入除数:");
int m = scanner.nextInt();
int result = n/m;
System.out.println("结果是:"+result);
//当try块发生异常,直接跳到catch块执行;
//可以改变程序的正常流向;
//try块要尽可能的小;
//注意要在catch语句中写入异常出现提示信息,以标注异常;
} catch (Exception e) {
// TODO: handle exception
System.out.println("Are you stupid?");
}finally {
//不管程序是否有异常,finally里面的代码都会被执行;
//finally里面面也可以放try catch;
System.out.println("我是finally");
}
System.out.println("程序结束~");
}
当有返回值时:
public int test(){
int n=10;
try{
n++;
//int m=9/0;
//n++;
return n;
}catch(Exception e){
n=n+1;
return n;
}finally{
n=30;
System.out.println("finally");
}
}
日志
主要用于记录系统运行中一些重要的操作信息;
public class Mylog {
public static void log(String message){
Date date = new Date();//获取当前时间
SimpleDateFormat simpleDateFormat=
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义时间格式
StringBuilder sBuilder = new StringBuilder();//可以更好的连接字符串
sBuilder.append("# ");
sBuilder.append(simpleDateFormat.format(date));
sBuilder.append(message);
sBuilder.append(" #");
FileWriter fw =null;
BufferedWriter bWriter=null;
try {
fw = new FileWriter("f:/Io/log.log",true);//要写入的文件
bWriter = new BufferedWriter(fw);
bWriter.write(sBuilder.toString());//转换为字符串存入文件
bWriter.newLine();//每写一行就换行
fw.flush();
bWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bWriter != null) {
try {
bWriter.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}