异常&线程

3 篇文章 0 订阅

异常&错误:处理&预防

异常的分类:checked&runtime

处理异常:

  1.   try...catch:多用一次捕获多次处理,多级处理的时候,父类异常要在后面处理
    try{
    可能存在异常的代码
    }
    catch(Exception e)
    {
    ....
    }

     

  2.   throw:抛出异常,传递到调用者,并停止当前方法;方法体内调用抛出异常实例
    throw new 异常类名(message OR args);

     

  3.   throws:应用于方法声明之上,表示该方法不处理异常只是通知调用者;声明异常的类型
    public class ThrowsDemo {
        public static void main(String[] args) throws FileNotFoundException {//声明 调用者jvm,中止
            read("a.txt");
        }
    
        // 如果定义功能时有问题发生需要报告给调用者。可以通过在方法上使用throws关键字进行声明
        public static void read(String path) throws FileNotFoundException {//声明,标记,通知调用者
            if (!path.equals("a.txt")) {//如果不是 a.txt这个文件 
                // 我假设  如果不是 a.txt 认为 该文件不存在 是一个错误 也就是异常  throw
                throw new FileNotFoundException("文件不存在");//抛出一个编译时异常对象
            }
        }
    }

     

  4.   finally:有一些特定的代码无论异常是否发生,都需要执行。另外,因为异常会引发程序跳转,导致有些语句执行不到。而finally就是解决这个问题的,在finally代码块中存放的代码都是一定会被执行的。配合try..catch使用。可以被中断不被执行:
    try{
    }
    catch(Exception e){//在这里如果插入System.exit(0);,则后面的finally代码块不执行
    }
    finally
    {
    }

     

  5. Regex:
    import java.regex.*;//Matcher,Pattern
    String str = "xxxxxxxxxx";
    Pattern pt = Pattern.compile(regex_str);
    Matcher m = pt.matcher(str);
    boolean isMatch = m.find();
    
    常用的方法:
    public boolean find() //
    public boolean find(int start)//重置此匹配器,然后尝试查找匹配该模式、从指定索引开始的输入序列的下一个子序列
    Matcher mc = pattern.matcher(str);
    mc.group();

    Matcher类提供了三个返回boolean值得匹配方法:matches(),lookingAt(),find(),find(int start),其中matches()用于全字符串匹配,lookingAt从字符串最开头开始匹配满足的子串,find可以对任意位置字符串匹配,其中start为起始查找索引值。
     

    Pattern pattern = Pattern.compile("Java");
    String test1 = "Java";
    String test2 = "Java1234";
    String test3 = "1234Java"
    Matcher matcher = pattern.matcher(test1);
    System.out.println(matcher.matches());//返回true
    matcher = pattern.matcher(test2);
    System.out.println(matcher.matches());//返回false
    
    matcher = pattern.matcher(test2);
    System.out.println(matcher.lookingAt())://返回true
    matcher = pattern.matcher(test3);
    System.out.println(matcher.lookingAt());//返回false
    
    matcher = pattern.matcher(test1);
    System.out.println(matcher.find());//返回true
    matcher = pattern.matcher(test2);
    System.out.println(matcher.find());//返回true
    matcher = pattern.matcher(test3);
    System.out.println(matcher.find(2));//返回true
    matcher = pattern.matcher(test3);
    System.out.println(matcher.find(5));//返回false
    

    Matcher类提供了start(),end(),group()分别用于返回字符串的起始索引,结束索引,以及匹配到到的字符串。

参考方法详解:--------------Pattern和Matcher方法 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值