0
点赞
收藏
分享

微信扫一扫

第七章 异常处理 #yyds干货盘点#

7.1 包装器

Java中的基本数据类型不是对象型(引用类型)。但是在程序中有时需要对对象而不是基本数据类型进行操作。因此,java里提供了一种叫做包装类(wrapper),它能够把基本数据类型包装成对象类型

Java中的包装器类有两个主要的作用

1.提供一种机制,将基本值“包装”到对象中,从而使基本值能够包含在为对象而保留的操作中,或者从带对象返回值的方法中返回。注意,java5增加了自动装箱和拆箱,程序员过去需手工执行的许多包装操作,现在可以由java自动处理了。

2.为基本值提供分类功能。这些功能大多数于各种转换有关:在基本值和String 对象间相互转换,在基本值和String 对象之间按不同基数转换,如二进制、八进制和十六进制等。

基本数据类型及包装类型的对应关系

boolean Boolean
byte Byte
char Character
double Double
float Float
int Integer
long Long
short Short

7.2 装箱拆箱

自动装箱和拆箱从Java 1.5开始引入,目的是将原始类型值转自动地转换成对应的对象。自动装箱与拆箱的机制可以让我们在Java的变量赋值或者是方法调用等情况下使用原始类型或者对象类型更加简单直接。

如果你在Java1.5下进行过编程的话,你一定不会陌生这一点,你不能直接地向集合(Collections)中放入原始类型值,因为集合只接收对象。通常这种情况下你的做法是,将这些原始类型的值转换成对象,然后将这些转换的对象放入集合中。使用Integer,Double,Boolean等这些类我们可以将原始类型值转换成对应的对象,但是从某些程度可能使得代码不是那么简洁精炼。为了让代码简练,Java 1.5引入了具有在原始类型和对象类型自动转换的装箱和拆箱机制。但是自动装箱和拆箱并非完美,在使用时需要有一些注意事项,如果没有搞明白自动装箱和拆箱,可能会引起难以察觉的bug。

package cn.webrx;

public class MyVar1 {
    public static void main(String[] args) {
        int i = 30;
        Integer n = 20;//自动装箱

        Integer nn = Integer.valueOf("30");
        System.out.println(n.intValue());
    }
}

7.3 异常概念

异常指的是在程序运行过程中发生的异常事件,通常是由外部问题(如硬件错误、输入错误)所导致的。在Java等面向对象的编程语言中异常属于对象。

异常(Exception)都是运行时的。编译时产生的不是异常,而是错误(Error)。

最开始大家都将程序设计导致的错误(Error)认定文不属于异常(Exception)。

但是一般都将Error作为异常的一种,所以异常一般分两类,Error与Exception。

package cn.webrx;

public class Excep1 {
    public static void main(String[] args) {
        int a = 30;
        int b = 0;
        System.out.println(a / b);  //java.lang.ArithmeticException

        //java.lang.StringIndexOutOfBoundsException
        //"hello".substring(100);

        int[] ns = {1,2,3};
        System.out.println(ns.length);
        System.out.println(ns[2]);
        System.out.println(ns[3]);

        String[] ss = {"aa","php"};

        show(ss);
        show(new String[]{"a","b"});
        show(ns);
    }

    public static void show(String[] sss) {

    }

    public static void show(int[] sss) {

    }
}

7.4 异常处理

try catch finally throw throws

package cn.webrx;

import java.util.Scanner;

public class Excep2 {
    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(System.in);
            System.out.print("\n请输入数字a");
            // java.util.InputMismatchException
            int a = sc.nextInt();
            System.out.print("\n请输入数字b");
            int b = sc.nextInt();

            // java.lang.ArithmeticException
            System.out.printf("%d / %d = %d \n", a, b, a / b);
        } catch (Exception e) {
            System.out.println("\n输入有误,必须都输入数字,且第二个b不能输入0.");
        }

        System.out.println("谢谢使用");
    }
}

try {
    Scanner sc = new Scanner(System.in);
    System.out.print("\n请输入数字a");
    // java.util.InputMismatchException
    int a = sc.nextInt();
    System.out.print("\n请输入数字b");
    int b = sc.nextInt();
    // java.lang.ArithmeticException
    System.out.printf("%d / %d = %d \n", a, b, a / b);
} catch (ArithmeticException e) {
    System.out.println("第二个b不能输入0");
} catch (InputMismatchException e) {
    System.out.println("输入有误,必须都输入数字");
} catch (Exception e) {
    System.out.println("\n系统未知异常。");
}finally {
    System.out.println("最终要执行的。");
}

7.5 声明异常

package cn.webrx;

public class SexException extends Exception{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public SexException() {

    }
    public SexException(String msg) {
        super(msg);
    }

}

7.6 抛出异常

package cn.webrx;

public class Student {
    private int id;
    private String name;
    private String gender;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) throws SexException {
        if("男".equals(gender) || "女".equals(gender)) {

        }else {
            throw new SexException("性别设置异常,必须为男或女");
        }
        this.gender = gender;
    }
}

测试

package cn.webrx;

public class Test {
    public static void main(String[] args) {
        Student stu = new Student();
        stu.setId(10);
        stu.setName("jack");
        try {
            stu.setGender("男2");
            int a = 10 / 20;
        } catch (SexException e) {
            System.out.println("性别设置错误。");
        } catch (ArithmeticException e) {
            System.out.println("分母为0了");
        } catch (Exception e) {
            System.out.println("未知exception");
        }
    }
}

7.7 finally块执行

package cn.webrx;

import java.io.IOException;

import org.jsoup.Jsoup;

public class Test2 {
    public static void main(String[] args) {
        Student stu = new Student();
        stu.setId(10);
        stu.setName("jack");
        try {
            stu.setGender("男");
            Jsoup.connect("http://mi.com").get();
        } catch (SexException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        show();
    }

    public static void show() {
        try {
            Jsoup.connect("http://www.baidu.com").get();
            System.out.println("try...");
            return;
        } catch (IOException e) {
            System.out.println("catch....");
            return;
        }finally {
            System.out.println("finally....");
        }
    }
}
举报

相关推荐

0 条评论