java基础8-异常和日志

一、异常

当程序遇到异常的时候,如何处理?
1。直接处理掉
2。抛给上层调用者处理

分类

异常分类:
 1. 检查性异常:Java.Lang.Exception及其子类
 2. 运行时异常:Java.Lang.RuntimeException及其子类
 3. 错误:Java.Lang.Error

自定义异常类

 1. 所有异常都必须是 Throwable 的子类。
 2. 检查性异常类,则需要继承 Exception 类。
 3. 运行时异常类,则需要继承 RuntimeException 类。

异常处理

 1. try....catch
 public static String createIfNotExist(String path) {  
            File file = new File(path);  
            if (!file.exists()) {  
                try {  
                    file.createNewFile();
                   
            
                } catch (Exception e) {  
                    System.out.println(e.getMessage());  
                }  
            }  
            System.out.println(file.getAbsolutePath());
            return path;  
        }  
 2. try ....catch....finally....
    public static boolean writeBytes(String filePath, byte[] data) {
        	FileOutputStream fos =null;
            try {  
                 fos = new FileOutputStream(filePath); 
                
                fos.write(data);  
                  
                return true;  
            } catch (Exception e) {  
            	e.printStackTrace();
                System.out.println(e.getMessage());  
            } finally {
				if(fos!=null)
					try {
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			} 
            return false;  
        }  
      

throws和throw

throws 作用于方法签名上
	声明方法抛出指定异常于上层调用者
	[修饰符] 返回值类型 方法名(参数列表) throws 异常类名
throw作用于方法体内
	让程序主动抛出一个异常
	throw new 类名();
栈轨迹
Exception 及其子类的 getStackTrace()方法可得到异常栈。
异常匹配
抛出异常时,系统会按照代码书写的顺序找出“最近”的处理程序,当找到处理程序后,终止后面的查找。

二、日志

java.util.logging包中的Logger类

2-1.日志等级

7个日志记录器级别
	SEVERE
	WARNING
	INFO
	CONFIG
	FINE
	FINER
	FINEST
设置级别为 logger.setLevel(Level.FINE),关闭所有级别记录则 Level.OFF

2-2记录日志的方法

 logger.级别名(消息名)或者   logger.log(级别常量,消息)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值