异常机制

在这里插入图片描述

    public class ExceptionDemo02 {
    	//模拟文件读取 自定义的异常
      public static void main(String[] args)  {
    	//写一个方法去读一个文件
    	  String str;
    	try {
    		str = readTxt("H:\\a.txt");
    		System.out.println(str);
    	} catch (PathNotFoundException e) {
    		System.out.println("异常被处理了");
    		System.out.println(e.getMessage());
    	}catch(FileFormatException e){
    		System.out.println("异常又被处理了");
    	}
    	
    	System.out.println("程序继续执行");
    	 
    }
      //path代表文件的地址
      public static String readTxt(String path) throws PathNotFoundException, FileFormatException{
    	  //判断路经地址是否合法 
    	  if(path.startsWith("H:")){
    		  throw new PathNotFoundException("文件路经不对,请重写");//没有这个异常,那么需要自己创建
    	  }
    	  if(path.endsWith(".txt")){
    		  throw new FileFormatException();
    	  }
    	  return "文件读取成功了 ";
      }
    }
    class PathNotFoundException extends Exception{
         private String message;
        public PathNotFoundException(){	
     	}
    	public PathNotFoundException(String message){
    		this.message =message;
    	}
    	public String getMessage() {
    		return message;
    	}
    	public void setMessage(String message) {
    		this.message = message;
    	}
    	
    }
     class FileFormatException extends Exception{
    	 public FileFormatException(){
    		 
    	 }
    	public FileFormatException(String message ){
    		super(message);  //父类的方法的值
    	}
    }

finally举例

    public class FinallyDemo02 {
    	public static void main(String[] args) {
    		System.out.println(demo02());
    	}
    	
    	public static String demo02(){
    		String str;
    		try{
    			str = "abc";
    			return str;
    		}finally{
    			str = "rty";
    		}
    	}
    	
    	public static Person demo01(){
    		Person p = new Person();
    		try{
    			// p的地址是 0x1111
    			// 给p赋值
    			p.setName("张无忌");
    			p.setAge(20);
    			// 遇到return p  挂起
    			return p;
    		}finally{
    			p = new Person();
    			// 继续给p的属性赋值
    			p.setName("杨过");
    			p.setAge(36);
    		}
    	}
    }
    
    
    
    class Person{
    	private String name;// 姓名
    	private int age;// 年龄
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    	@Override
    	public String toString() {
    		return "Person [name=" + name + ", age=" + age + "]";
    	}
    	
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值