异常
异常分类:1、编译异常:要求开发者必须处理,如果不处理会编译错误
2、运行期异常:开发者可处理,也可以不处理,不处理也可以通过编译
finally: 1、无论是否有异常都会执行的语句块,如果在try块或catch块总有return语句,那么会跳出该方法前执行finally。一般用于流的关闭,数据库的关闭等资源 回收动作
2、在finally块前加System.exit(0);会不执行后面的finally
try{ JFrame j = null; j.setSize(400,300); //null调用方法会报异常 } catch(NullPointerException e){ System.out.println("空指针异常"); } catch(Exception e){ System.out.println("发生异常"); } finally{ System.out.println("finally代码"); } System.out.println("异常外代码"); 输出结果: 空指针异常 finally代码 异常外代码
public class FinallyTest { private static String str = ""; public static void foo(int x){ try{ if(x == 0){ int y = 9/0; } str += "1"; }catch(Exception e){ str += "2"; return; } finally{ str += "3"; } str += "4"; } public static void main(String[] args) { foo(0); foo(1); System.out.println(str); } } 23 134
public class Test { public static void main(String[] args) { int[] strs = {1,2,3,5,7}; int sum = 0; try{ for(int i = 0 ;i<=5;i++){ sum += strs[i]; //下标越界跳出 } System.out.println(sum); }catch(Exception e){ System.out.println("出现异常"); } finally{ System.out.println("finally"); } } } 出现异常 finally
正则表达式:
[]:匹配[]中定义的任意字符
{3,10}:前一个规则,最少出现3次,最多出现10次
{3,}:前一个规则,最少出现3次,没有上限
{3}:前一个规则只能出现3次,不多也不能少
|:或者 (ab|cd)要用()包住
[\\u4e00-\\u9fa5]匹配汉字
+:等价于{1,}前一个规则至少出现一次,没上限
*:等价于{0,}前一个规则可以不出现,也可以出现多次
?:{0,1}前一个规则,可以不出现,最多出现1次
。:等价于任意字符
\\d:等价于[0-9]
\\w:等价于[a-zA-Z0-9_]匹配字母。数字。下划线
\\s:匹配空格,回车,换行
public static void main(String[] args) { String s=JOptionPane.showInputDialog(null,"请输入一个网址"); String rex="[a-zA-Z]{3,20}@[a-zA-Z0-9]{2,10}[.](com|cn|net)"; if(s.matches(rex)){ JOptionPane.showMessageDialog(null, "合法化"); } else{ JOptionPane.showMessageDialog(null, "不合法"); } }
拆分字符串获取数组
// //去除说有数字 // String s="safds234h5dfh153hkj1hg3k"; // s=s.replaceAll("\\d+",""); // System.out.println(s); //按*拆分字符串成一个数组。打印数组元素 // String a="abc****cde*ppp*xx"; // String[] array=a.split("[*]+");//*是关键字{1,}所以要用[]包裹 // for(String s:array){ // System.out.println(s); // } // StringBuffer sb=new StringBuffer("abcdf"); sb.append("****"); System.out.println(sb); sb.delete(2, 4); System.out.println(sb); sb.insert(2, "11111"); System.out.println(sb); sb.reverse(); System.out.println(sb); }
public static void main(String[] args) { String s="http://localhost:8088/abc?name=john&age=12&sex=男&phone=12315&ede=1650"; s=s.substring(s.indexOf("?")+1); System.out.println(s); Properties pro=new Properties(); String[]array=s.split("&"); for(String a:array){ System.out.println(a); String[]arr=a.split("="); pro.setProperty(arr[0], arr[1]); } try { pro.store(new FileWriter("info.txt"),null); } catch (Exception e) { System.out.println("没找到"); } }