zoukankan      html  css  js  c++  java
  • 三异常机制

    异常的概念_分类

          异常(Exception 也称例外)就是在程序的运行过程中所发生的不正常的事件,它会中断正在运行的程序
       所需的文件找不到;
       网络连接不通或中断;
       算术运算错(被零除...);
       数组下标越界;
       装载一个不存在的类或者对null对象操作;
       类型转换异常;

    异常处理的方式一  _捕获异常      

      捕获异常所使用的关键字try, catch,finally
          try-catch-finally的使用:

      ·try—catch 的组合

      (发生异常,异常代码段不执行):

    package com.zqf.Exception;
    import java.util.Scanner;
    public class TestTryCatch {
     public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      try{
       System.out.println("请输入被除数:");
          int numA = input.nextInt();
          System.out.println("请输入除数:");
          int numB = input.nextInt();
          int result = numA / numB;
          System.out.println(numA + "/" + numB+ "="+result);
          }catch(Exception e){        //相当于Exception e = new ArithmeticException() 多态的表示形式,父亲引用指向了子类对象
           e.printStackTrace( );    //调用了打印堆栈信息的方法
          }
      System.out.println("程序结束,谢谢您的使用");
     }
    }

      ·try—finally组合

      (finally是无论是否产生异常,都执行的代码,但是有一种情况finally不执行,即退出虚拟机):
    package com.zqf.Exception;
    import java.util.Scanner;
    public class TestTryFinally {
     public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      try{
       System.out.println("请输入被除数:");
          int numA = input.nextInt();
          System.out.println("请输入除数:");
          int numB = input.nextInt();
          int result = numA / numB;
          System.out.println(numA + "/" + numB+ "="+result);
          //退出Java虚拟机
          System.exit(0);
          }finally{
           System.out.println("finally中的代码");
                    }
     }
    }

      ·try—catch—finally:

      a.正常情况:执行try-finally
      b.异常情况类型不想匹配,执行try-finally
      c.异常情况:类型不匹配,则先执行完fianlly语句,再回头执行return语句
    package com.zqf.Exception;
    import java.util.Scanner;
    public class TestTryCatchFinally {
     public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
     try{
      System.out.println("请输入被除数:");
         
      int numA = input.nextInt();
         System.out.println("请输入除数:");
         int numB = input.nextInt();
         int result = numA / numB;
         System.out.println(numA + "/" + numB+ "="+result);
         }catch(ArithmeticException e){
          System.out.println("除数不能为0");
          System.out.println("获取异常的字符串描述"+e.getMessage());
         }finally{ 
          System.out.println("finally中的代码");
         }
     }
    }

    异常的处理方式二—声明异常

      ·声明异常的关键字throws(声明)

      方法名的后面,用于声明该方法可能会产生一个异常,如果方发声明的是Exception类型的异常或者是CheckedException异常,要求方法的调用出必须做处理,
               1.继续使用throws向上(方法的调用处)声明
               2.使用try-catch-finally进行处理
                                             如果声明的是RuntimeException类型的异常,那么方法的调用处可处理可不处理。
    package com.zqf.throwsoo;
    public class TestThrows {
     public static  void show()throws Exception{
      
     }
     public static void main(String[] args){//throws Exception{                 //声明异常
      //调用本类中的静态方法show()
      try{
      show();
     }catch(Exception e){
      e.printStackTrace( );
      }
     }
    }

     ·继承关系中的声明异常

      1.父类的方法声明了Exception类型的异常,子类在重写方法时,可以声明也可以不声明。但是如果子类重写后的方法使用super关键字调用父类的方法,那么要求必须对异常进行处理。
             2.如果父类的方法没有异常,那么子类的方法如果一定会有Exception或Checked异常,要求子类必须自己使用try-catch处理,或者给父类方法加上异常的声明。
             3.如果子类在重写父类的方法时,产生的异常是RuntimeException异常时,那么可以不用处理
          throw抛出异常对象(写在方法里)
     在捕获一个异常前,必须有一段代码先生成异常对象并把它抛出。这个过程我们以手工做,也可以由JRE来实现,但是他们调用的都是throw子句。
    package com.zqf.throwsoo;
    public class TestThrow {
     public static void show(){
      try {
       throw new Exception();
      } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
     }
     public static void main(String[] args) {
      show();
     }
    }

      ·throws 与 throw

         1.throws用于声明方法可能会产生的异常类型
            throw手动抛出异常对象
         2.throws写在方法名称后面
            throw用于写在方法里

    常见简单异常的解决办法:

          常见的异常类型:
                1.运行时异常RuntimeException
       a.算术异常 ArithmeticException
       b.空指针异常 NullPointerException
       c.类型转换异常 ClassCastException
       d.数组下标越界 ArrayIndexOutOfBoundException
       e.期望的数据类型与实际输入类型不匹配InputMismatchException
    package com.zqf.Exception;
    import java.util.Scanner;
    public class TestRuntimeException {
     public static void main(String[] args) {
      //(1)算术异常
      int b = 0;
      if(b!=0){
       int result = 1/b;
      }else{
       System.out.println("对不起除数不能为0");
      }
      //(2)空指针异常,没有创建对象(new)而调用了对象的属性或方法
      String str = null;
      if(str!=null){
      System.out.println(str.length());
         }
      //(3)类型转换异常ClassCastException
      Animal dog = new Dog();      //向上类型转换
      if (dog instanceof Cat){    //instanceof用来判断指定的对象是否真实属于指定的类型,返回值是boolean
      Cat c = (Cat)dog;        //向下类型转换,转换成真实的子类对象
      }
      //(4)数组下标越界ArrayIndexOutOfBoundsException
      int []arr= {11,22,33};     //长度3
      int index = 3;
      if(index<arr.length-1){
       System.out.println(arr[index]);
      }else{
       System.out.println("数组下标越出了边界");
      }
      //(5)期望的数据类型与输入的数据类型不相匹配InputMismatchException
      Scanner input = new Scanner(System.in);
      if(input.hasNextInt()){     //hasNextInt()判断输入的是否是整数,返回值为Boolean,    true or false
       int a = input.nextInt();
       System.out.println(a);
      }else{
       System.out.println("对不起,输入的类型与期望的类型不匹配");
      }
      
     }
    }
    class Animal{   }
    class Dog extends Animal{}
    class Cat extends Animal{}
                2.检查时异常Checked Exception
     a.SQLExecption
     b.IOException
     c.ParseException
                 要求必须做处理,(1)throws向上声明   ;  (2)try-catch-finally
    package com.zqf.Exception;
    import java.io.File;
    import java.io.IOException;
    public class TestCheckedException {
     public static void main(String[] args) throws IOException {
      //检查时异常,N多个程序在编译期间必须处理的异常的一总称
      File f = new File("C:\a.txt");
      f.createNewFile();    //在C盘创建一个名词为a.txt文件
     }
    }

    自定义异常:

          1.为什么需要自定义异常:在程序中,坑你会遇到任何标准异常类都没有充分的描述清楚问题,这种情况下可以创建自己的异常类
          2.自定义异常的步骤:a. 继承Exception或RuntimeException    b.定义构造方法    c.使用异常
     1 package com.zqf.Exception;
     2 import java.util.Scanner;
     3 public class TestSexException {
     4  public static void main(String[] args) {
     5   Scanner input = new Scanner(System.in);
     6   System.out.println("请输入您的性别:");
     7   String gender = input.next();
     8   if("男".equals(gender)||"女".equals(gender)){
     9    System.out.println("性别录入正确");
    10   }else{
    11    try {
    12     throw new SexException("性别只能是男或者女");
    13    } catch (SexException e) {
    14     // TODO Auto-generated catch block
    15     e.printStackTrace();
    16     System.out.println(e.getMessage());
    17    }
    18   }
    19  }
    20 }
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    常用Linux命令:ls/cd/pwd/mkdir/rm/mv/cp
    设计模式(5)---代理模式
    设计模式(4)---装饰模式
    设计模式(3)---基本原则
    设计模式(2)---策略模式
    设计模式(1)---简单工厂模式
    linux系统硬件配置查看方法
    boost.asio系列(一)——deadline_timer
    ubuntu 安装JDK
    计算图像数据集的RGB均值
  • 原文地址:https://www.cnblogs.com/zqfdgzrc/p/10435582.html
Copyright © 2011-2022 走看看