Abnormal architecture; exception handling mechanism; Exceptions Exceptions compile time and run; the Throwable conventional method; custom exception (Java Day17)

First, abnormal

  • Overview: The literal meaning is not normal. Appeared in the process of compiling or running java code will not compile or run result in the affected cases are all abnormal.
  • Reflect: Class class using the various abnormal phenomenon described [cause of the abnormality, the position, type, description and other attributes]
  • Use: the object class object throws an exception class objects contain the cause of the abnormality occurs, the location, type, detailed description of other specific data.
  • Abnormal system

  • system:
  1. ​ Throwable
  2. Error
  3. Exception
  4. ​ RuntimeException
  • Explanation:
  1. Throwable: the exception is all top-level parent, extracts all the common attributes and abnormal behavior
  2. Error: the error; exception belonging to a large branch, means that the programmer does not capture the exception processing can be performed. For example: memory overflow, stack overflow
  3. Exception: Abnormal; are abnormal in other major branch, means that we can use the code catches an exception object related to abnormal processing. For example: a null pointer exception, abnormality such as division by zero anomalies
  4. RuntimeException: abnormal operation, it is those compiled without problems, running abnormal phenomenon will occur. For example: a null pointer exception divide by zero abnormality
  • Exception handling

  1. Exception handling: that is the way we solve unusual objects
  2. Treatment: manual handling, jvm process
  • Manual handling: we need to own the code related to abnormal approach.

  1. Disclaimer exception: when it came to the exception that they are not treated, the type of exception declarations away to someone else to deal with [the] use the keyword throw out an exception throws an exception after the declaration of the type of method statements
  2. Scene: the method body method may have an abnormal occurrence
  3. Format: Method name (parameter list) throws Exception {Type} method thereof
  • note:
  1. Unusual statement does not represent the exception object will be generated, resulting in a process to be thrown out, no not treated, the statement still have your statement [statement on the deal did not bother me count]
  2. Unusual statement did not console output and other effects, only a statement telling people [abnormal] throw out the effect of abnormal results [abstract] type of throw
  3. Exceptions Exception produce a statement after the throw to someone else if not handled or processed by jvm; The following code can not be executed, if the exception handler others, the following code continues to execute.

The sample code

com.ujiuye.demo Package; 
Import a java.io.FileInputStream; 
Import java.io.FileNotFoundException; 
public  class Demo_Exception {
     public  static  void main (String [] args) throws a FileNotFoundException {
         // create the object when using the construction method, structure throw out a method FileNotFoundException exception type
         // who use it who threw a main method in the method body will have to use the body to deal with this anomaly
         // main method of treatment you can also do not want to continue to throw out the use of unusual statement 
        FileInputStream fis = new new FileInputStream ( " a b.txt \\ " );
         // abnormal declares the method body will produce the abnormal it?
        //When the project is not a \\ b.txt running error means that the object had abnormal
         // works when there is a \\ b.txt running does not mean that error exception object no 
    } 
}

 

  • Catch exception handling:  can occur when the body of abnormal method, the method body themselves to capture this exception object, and related content to handle the exception, not throw people deal with their own [own] angered disaster
  • Format:
  1. ​ try....catch
  2. ​ try...catch..finally
  3. ​ try...finally
  • The first format: try ... catch
  • The specific format : the try {  possible exception code segment  } catch ( Exception type variable name ) { exception resolution code segment }
  1. try: Try meaning. Try to execute likely to have abnormal code
  2. catch: capture means, if an exception occurs in the try, the exception object is captured and processed
  3. (): Write captured catch the exception object to the
  4. {}: Writing code to handle exceptions
  • Implementation process:
  1. Performing abnormality, the code of which code does not try top-down occurs during the execution of the catch block skip [ineffective]
  2. Try exception among the code generation; trigger catcher to catch block where the exception occurred abnormal object, code execution will jump from the order of the exception block is performed directly to the catch, the catch block is completed continue following code.
  3. catch words in brackets if abnormal, it can also be captured handle claims processing

The sample code

com.ujiuye.demo Package; 
Import a java.io.FileInputStream; 
Import java.io.FileNotFoundException; 
public  class Demo_Exception02 {
     public  static  void main {(String [] args) 
        the System. OUT .println ( " started " ); // 1
         // this line of code has attracted an abnormality handling their own processing of the disaster ... the catch the try   
        the try {
             // file is abnormality does not occur in the presence of 
            the FileInputStream FIS = new new the FileInputStream ( " a b.txt \\ " ); 
            System. OUT .println ( "No abnormal execution " );
             // file does not exist in the abnormality occurs will here catch to catch exceptions, the code execution jumps to catch 
            the FileInputStream FIS1 = new new the FileInputStream ( " B b.txt \\ " ); 
            the System. OUT .println ( " attempt during execution " ); // 2 there will not carry out the execution without exception is 
        } the catch (FileNotFoundException E) { 
            System. OUT .println ( " this is a file can not be found exception, have been processed ." ) ; // 4 catch the exception and execute
             // the catch in the code generated an exception that how we deal with how to deal with possible declaration may be captured 
            try {
                FIS the FileInputStream = new new the FileInputStream ( " A b.txt \\ " ); 
            } the catch (a FileNotFoundException E1) { 
                . The System OUT .println ( " Exception Handling a " ); 
            } 
        } 
        
        . The System OUT .println ( " code is completed! " ); // 3 
    } 
}

 

 

  • Deformation format: a plurality of catch block format

​         try {有可能有异常的代码段} catch(异常对象1){解决异常1的方案} catch(异常对象2){解决异常2的方案}....catch(异常对象n){解决异常n的方案}

  • 注意事项:【掌握的面试的时候经常被问到里面的相关知识点】
  • 多个 catch 块,执行的时候只会执行其中之一或者一个也不执行
  • 多个异常有了同时触发的条件,实际以第一个被触发的异常为准,其他的异常不会被触发,对应执行的是第一个异常的 catch 块,其他 catch 块不管【不执行】
  • ​ catch 块中不可以写 break,但是可以写 return 提前【异常处理完】结束方法
  • catch 的多个异常对象之间如果有子父类关系,catch 异常对象的顺序有要求:自上而下遵循由小到大【子类类型对象在前,父类类型对象在后】
  • 捕获的异常对象处理的时候选择catch块时遵循:
  1. 优先匹配自己类型的对象的catch块
  2. 没有自己类型的对象catch块,就近执行最近的父类的对象的catch块
  3. 自己和父类对象的catch块都没有,那就报错
  • ​jdk1.7之后,异常捕获时异常类型可以使用|【或】表示【多种不同的异常想要用相同的处理方式的时候可以使用|】
  1. 多种异常类型对象,可以使用相同的处理方式
  2. ​异常类型是相互独立没有关系的类型【不能有继承关系】
  3. ​ 格式:catch(异常类型1 | 异常类型2 |异常类型3 对象名){  }

代码示例

package com.ujiuye.demo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Demo_Exception03 {
    public static void main(String[] args)  {
        System.out.println("开始执行");//1
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int num = sc.nextInt();
        //这行代码有异常  进行处理  自己惹来的祸自己处理  try...catch  
        try {
            //文件是存在的不会发生异常  //异常1 FileNotFoundException
            FileInputStream fis = new FileInputStream("a\\b.txt");
            System.out.println("无异常执行");
            //文件是不存在的会发生异常   catch就会到这里捕获异常,代码执行跳转到catch中
            FileInputStream fis1 = new FileInputStream("b\\b.txt");
            System.out.println("尝试执行过程中");//2     有异常不执行了  无异常就执行
            //异常2:除数为0的异常  ArithmeticException
            System.out.println(100/num);//第一个被触发了
        } catch (FileNotFoundException | ArithmeticException | NullPointerException e) {
            System.out.println("这是一个文件无法找到的异常,已经处理");//4  捕获异常并执行
            //break;
            //return ;//结束方法的
        }/*catch (ArithmeticException e) {
            System.out.println("这是一个文件无法找到的异常,已经处理");
            //System.out.println("这是一个除数为0异常");
        }*//*catch (IOException e) {//他是捕获到的异常对象的父类
            System.out.println("这是一个io的异常,已经处理");//4  捕获异常并执行
        }*//*catch (Exception e) {//爷爷类  执行爷爷类
            System.out.println("这是一个编译异常,已经处理");//4  捕获异常并执行
        }*/
        
        System.out.println("代码执行完毕!");//3
    }
}

 

  • 第二种:try...catch...finally
  • ​ 具体格式:​ try {有可能产生异常代码} catch(异常对象){对异常对象的解决方案} finally {无论有无都必须要执行的代码}
  • 特点:finally 里面的代码不管try 当中的代码是否会发生异常它肯定会执行的。
  • ​ 使用场景:io 流对象关闭使用 finally。
  • 注意事项:
  1. 中间的 catch 块可以有多个
  2. finally 不可以单独使用,必须跟在 try 代码块后面

代码示例

package com.ujiuye.demo;
import java.io.FileInputStream;
public class Demo_Exception04 {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new  FileInputStream("b\\b.txt");
            //写在这没有异常可以打印输出  有异常输出不了
            //System.out.println(123);
        } catch (Exception e) {
            System.out.println("异常已处理");
            //没有异常 输出不了   有异常输出了
            //System.out.println(123);
            return;
        }finally {
            System.out.println(123);//百分百的保证代码执行
        }
        //必须要在控制台输出一个123
        //如果catch块中产生异常或者有return  有可能输出不了
        //System.out.println(123);
    }
}

 

  • 第三种处理方式【不处理异常,纯粹的为了finally】
  • ​ 格式:try { 有可能出现异常的代码 } finally { 必须要执行的代码 }
  • ​ 不怎么用;这种格式并不是处理异常的,单纯就是为了finally的使用,异常根本就没有被处理

代码示例

package com.ujiuye.demo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Demo_Exception05 {
    public static void main(String[] args) /*throws FileNotFoundException*/ {
        try {
            try {
                FileInputStream fis = new  FileInputStream("b\\b.txt");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //FileInputStream fis = new  FileInputStream("b\\b.txt");
        }/* catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/ finally {//finally不能单独使用,必须需要try
            System.out.println("nihaoha,bingdu");
        } 
    }
}

 

  • 处理异常使用格式注意事项:
  1. try 代码块可以单独使用【单独使用没有意义】变换也不能单独使用
  2. catch 代码块不能单独使用,不能离开 try 代码块。
  3. finally 不能单独使用,要结合 try 代码块使用。

二,jvm的异常处理方式

  • jvm 是作为执行者,调用的 main 方法;其他方法都需要通过main方法直接或间接的调用,异常一旦产生,自己又不想自己解决采用声明的方式来抛出异常,不停抛抛来抛去最终抛到 jvm,jvm 最后的一个调用者抛不了必须要自己处理。
  • jvm 的处理方式:先把程序给停止 然后捕获异常处理【把异常对象中的相关信息进行打印】。
  • jvm 异常的处理和捕获处理的区别?
  1. ​ 捕获处理异常:catch 块下面的代码可以继续执行出效果【jvm没有停止】
  2. ​ jvm 处理异常:产生异常代码处后面的所有代码都不能够执行了【jvm直接停止】

三,异常分类

  • 编译异常在代码编译过程中会对 相关代码进行格式和语法的检查,如果不满足就会直接报错提示,不会将错误放到运行去。编译异常都属于Exception的子类,必须要进行处理才可能继续执行
  • 运行异常在编译的时候不会对代码进行一些相关的检查,只有在运行的时候才会发现有问题的异常。运行异常都是RuntimeException的子类,可以处理也可以不处理【交给jvm来处理】一般的运行异常选择不处理

四,异常体系的常用方法

  • ​ 异常体系的方法全部定义在 Throwable 类中,其他异常类没有定义任何的方法,都是继承 Throwable 中的方法。
  • 构造方法:
  1. Throwable(): 创建一个没有任何异常信息的异常对象
  2. Throwable(String message): 创建一个只有异常信息描述的对象
  3. Throwable(Throwable t): 创建一个有异常原因的异常对象
  4. Throwable(String message,Throwable t): 创建一个有异常信息和异常原因的异常对象
  • 普通方法:
  1. getCause: 获取异常对象的异常原因
  2. getMessage: 获取异常的提示详细信息【常用】
  3. ​ toString: 获取异常对象的详细属性信息
  4. ​ printStackTrace: 打印异常的调用地址信息【常用】

代码示例

package com.ujiuye.demo;
public class Demo {
    public static void main(String[] args) {
        Throwable t1 = new Throwable();
        Throwable t2 = new Throwable("这是一个角标越界异常");
        Throwable t3 = new Throwable(t2);
        Throwable t4 = new Throwable("这是一个类型转换异常",t1);
        System.out.println(t1.getCause());
        System.out.println(t1.getMessage());
        System.out.println(t1.toString());
        t1.printStackTrace();
        System.out.println("===============");
        System.out.println(t2.getCause());
        System.out.println(t2.getMessage());
        System.out.println(t2.toString());
        t2.printStackTrace();
        System.out.println("===============");
        System.out.println(t3.getCause());
        System.out.println(t3.getMessage());
        System.out.println(t3.toString());
        t3.printStackTrace();
        System.out.println("================");
        System.out.println(t4.getCause());
        System.out.println(t4.getMessage());
        System.out.println(t4.toString());
        t4.printStackTrace();
    }
}

 

Guess you like

Origin www.cnblogs.com/nastu/p/12505771.html