异常基础内容

  • Post author:
  • Post category:其他


复习{



常用类: java.util.*

    java.lang 不需要导包


Arrays:

​ sort(arr); toString();

​ copyOf();



Random:
  nextInt(11)+10; 10


Math: random(); 返回 0-1 随机值
 abs(int a ); 绝对值
 max(int a , int b);
 min(int a , int b);
 sqrt(int a); 
 pow(int a, int b);
 PI;


Scanner: new Scanner(System.in); 流
控制台输入 	 
  next();	 按空格截取	 	
  nextLine(); 按回车截取
  nextInt();

正则表达式: java.util.regex

Pattern : 编译正则表达式 [a-z]

Pattern p = Pattern.complie(“[a-z]”);

Matcher m = p.machter("用户输入的值");
 
boolean b = m.matches();

Matcher: 匹配的

返回true false

[^a-z] ,() , {}

/


1


, $ 结束

[asd] [a-zA-Z] [0-9]

\d ,\D ,\w , [^a-zA-Z0-9_] \W

{n} ,{n,} ,{n,m}

  • : 0个 或 多个
  • : 1个 或多个

    ? : 0 或 1个

    x|y :

}



java的异常体系: 异常现象



生活中的异常 就是 :打乱了生活秩序


程序中异常: 会影响程序的正常运行,程序员可以解决掉


异常:Exception 程序员能解决的

​ int i= 1/0;

​ ArithmeticException



错误:Error 程序员解决不掉的

​ StackOverflowError 栈溢出错误



预知到程序在运行时会出现问题:

所以java研发者编写了一套异常体系,提供信息给你, 这样便于发现问题, 解决问题



异常体系:


Throwable:

构造方法:

new Throwable();

new Throwable(String message);

方法:

 1. String result = getMessage(); 获取异常信息 
  	 	 例如 /by zero
 2. printStackTrace(); 返回并打印信息 

|– Error:

|– VirtualMachineError

|– StackOverflowError 栈溢出

|– OutOfMemoryError 内存泄漏

|– Exception:

|– IOException I/O流 异常

|– RuntimeException 运行时异常

|– IllegalArgumentException 非法参数异常

|– ArithmeticException 数学异常

|– ClassCastException 类型转换异常

|– IndexOutOfBoundsException

|– ArrayIndexOutOfBoundsException

|– StringIndexOutOfBoundsException

|– NullPointerException 空指针异常 就是 null.东西了

​ |– CheckedException是不存在的 受检查异常,只针对 编辑器 eclipse , idea

既然异常已经出现了 ,java是 处理异常的呢?

java中 有两种 处理异常的方式:

|– try…catch 捕获异常 自身解决

 try{
 	可能产生问题的代码
 }catch(Exception e){
 	 e.printStackTrace();
 }
 
 只能发现问题, 解决不了问题, 
 问题是由程序员解决
catch (ArithmeticException | NullPointerException | ClassCastException e) {    	 
    	 //同级类别,公用一个变量 
}  	 
catch (ArithmeticException e) {	 
	//必须是从小到 大 , 子类在先 父类在后
	e.printStackTrace();
	System.out.println("====");
	//异常体
}catch(NullPointerException e){
	e.printStackTrace();
}catch(ClassCastException e){
	e.printStackTrace();
}catch(Exception e){
	e.printStackTrace();
}

补充:

try{
//捕获异常加 关闭资源
}catch(Exception e){     

}finally{
	//这个位置代码一定执行
}

try{
	//专门用来关闭资源
}finally{
	//这个位置代码一定执行
}

finally块儿中的代码一定执行 吗?

作用: 用来 关闭 ,释放 资源,例如数据库, I/O流的数据传输

一般情况下 会执行,

但是特殊情况下 不会执行:

例如:

  1. 在try块儿中 执行了 System.exit(0);

    这叫强制退出,不会执行finally块儿

  2. 在进入到 try块儿前 出现了异常 ,那么也不会执行finally块

    一般用于 预期

    int i = 1/0;

jvm虚拟机 也给处理

|– throw 抛出,抛给 了 别人

 public static void div(int a, int b )throws ArithmeticException,NullPointerException ,Exception  {
	if(b == 0){
		//抛出异常
		throw new Exception();
	}
 }

抛出后 一定要 try…catch 或 throw 即可

自定义异常:

如果java异常体系中的 类型 不能满足我们了



  1. ↩︎



版权声明:本文为Loare原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。