@nextleaf
2018-08-16T03:48:02.000000Z
字数 11199
阅读 967
Java 包装类 异常 转换 工作日志
1). 抽象类中的方法可以有方法体,就是能实现方法的具体功能,但是接口中的方法不行。
2). 抽象类中的成员变量可以是各种类型的,而接口中的成员变量只能是 public static final 类型的。
3). 接口中不能含有静态代码块以及静态方法(用 static 修饰的方法),而抽象类是可以有静态代码块和静态方法。
4). 一个类只能继承一个抽象类,而一个类却可以实现多个接口。
| 基本数据类型 | 对应的包装类 |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| char | Character |
| float | Float |
| double | Double |
| boolean | Boolean |
//装箱:自动将基本数据类型转换为其对应的包装类.//拆箱:自动将包装类型转换为基本数据类型.int i = 9;//Integer(int) 已经过时了java.net.URLDecoder 中的方法decode(String encodeStr) 这个方法已经过时,应该使用双参数decode(String source, String encode)。//Integer integer=new Integer(i);Integer integer = Integer.valueOf(i);System.out.println(integer);//自动拆箱int ii = integer;//'Float(java.lang.String)' 已经过时了//Float f=new Float("10.9f");Float f = Float.valueOf("10.9f");System.out.println(f);Booleanb1 = Boolean.valueOf("true"),//falseb2 = Boolean.valueOf("sdfghgfd"),b3 = Boolean.FALSE;System.out.println(b1);System.out.println(b2);System.out.println(b3);//引用类型默认值nullBb bb = new Bb();System.out.println(bb.aBoolean);
int i1 = integer.intValue();float f2 = f.floatValue();boolean bL = b3.booleanValue();
String str = "996";//只产生一个对象int i1 = Integer.parseInt(str);//会多产生一个对象int i1 = Integer.valueOf(str.trim()).intValue();//'new Boolean(String)' 已经过时了boolean b = Boolean.parseBoolean("true");Integer integer = Integer.parseInt("668");
//会产生两个String对象str=i1+"";//只产生一个对象str = String.valueOf(i1);
异常发生的原因有很多,通常包含以下几大类:
1. 用户输入了非法数据。
2. 要打开的文件不存在。
3. 网络通信时连接中断,或者JVM内存溢出。
- 检查性异常:
最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。- 运行时异常:
运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。- 错误:
错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。
注:
应用程序没有处理抛出的异常时,会交由JVM来处理这个异常。结果是:
当前线程会停止运行,异常触发点后面的代码将得不到运行。
异常栈信息会通过标准错误流输出。

| 异常 | 描述 |
|---|---|
| ClassNotFoundException | 应用程序试图加载类时,找不到相应的类,抛出该异常。 |
| CloneNotSupportedException |
当调用 Object 类中的 clone 方法克隆对象,但该对象的类无法实现 Cloneable 接口时,抛出该异常。
|
| IllegalAccessException | 拒绝访问一个类的时候,抛出该异常。 |
| InstantiationException |
当试图使用 Class 类中的 newInstance 方法创建一个类的实例,而指定的类对象因为是一个接口或是一个抽象类而无法实例化时,抛出该异常。
|
| InterruptedException | 一个线程被另一个线程中断,抛出该异常。 |
| NoSuchFieldException | 请求的变量不存在 |
| NoSuchMethodException | 请求的方法不存在 |
| 异常 | 描述 |
|---|---|
| ArithmeticException | 当出现异常的运算条件时,抛出此异常。例如,一个整数"除以零"时,抛出此类的一个实例。 |
| ArrayIndexOutOfBoundsException | 用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引。 |
| ArrayStoreException | 试图将错误类型的对象存储到一个对象数组时抛出的异常。 |
| ClassCastException | 当试图将对象强制转换为不是实例的子类时,抛出该异常。 |
| IllegalArgumentException | 抛出的异常表明向方法传递了一个不合法或不正确的参数。 |
| IllegalMonitorStateException | 抛出的异常表明某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程。 |
| IllegalStateException | 在非法或不适当的时间调用方法时产生的信号。换句话说,即 Java 环境或 Java 应用程序没有处于请求操作所要求的适当状态下。 |
| IllegalThreadStateException | 线程没有处于请求操作所要求的适当状态时抛出的异常。 |
| IndexOutOfBoundsException | 指示某排序索引(例如对数组、字符串或向量的排序)超出范围时抛出。 |
| NegativeArraySizeException | 如果应用程序试图创建大小为负的数组,则抛出该异常。 |
| NullPointerException |
当应用程序试图在需要对象的地方使用 null 时,抛出该异常
|
| NumberFormatException | 当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。 |
| SecurityException | 由安全管理器抛出的异常,指示存在安全侵犯。 |
| StringIndexOutOfBoundsException |
此异常由 String 方法抛出,指示索引或者为负,或者超出字符串的大小。
|
| UnsupportedOperationException | 当不支持请求的操作时,抛出该异常。 |
检查性异常继承java.lang.Exception类。非检查性异常继承自java.lang.RuntimeException类。
对异常对象的处理(catch):
public String getMessage()返回关于发生的异常的详细信息。这个消息在Throwable 类的构造函数中初始化了。
public Throwable getCause()返回一个Throwable 对象代表异常原因。
public String toString使用getMessage()的结果返回类的串级名字。
public void printStackTrace()打印toString()结果和栈层次到System.err,即错误输出流。
public StackTraceElement [] getStackTrace()返回一个包含堆栈层次的数组。下标为0的元素代表栈顶,最后一个元素代表方法调用堆栈的栈底。
public Throwable fillInStackTrace()用当前的调用栈层次填充Throwable 对象栈层次,添加到栈层次任何先前信息中。
(通常用来捕获检查性异常)
try{// 程序代码1}catch(异常类型1 异常的对象名1){// 程序代码2}catch(异常类型2 异常的对象名2){// 程序代码3}catch(异常类型2 异常的对象名2){// 程序代码4}
如果try代码中发生异常,异常被抛给第一个 catch 块(如果发生的异常包含在 catch 块中,异常会被传递到该 catch 块)。
如果抛出异常的数据类型与 "异常类型1" 匹配,它在这里就会被捕获,执行该catch块,后面的catch块将被忽略,
如果不匹配,它会被传递给第二个 catch 块,如此,直到异常被捕获或者通过所有的 catch 块。
如果没有catch块匹配,则先执行finally。
如果多个catch中的"异常类型"是“包含”关系,要将子类写在前面父类写在后面。
无论是否发生异常,finally 代码块中的代码总会被执行
在 try块中即便有return,break,continue等改变执行流的语句,finally也会执行
finally中的return 会覆盖 try 或者catch中的返回值
finally中的return会抑制(消灭)前面try或者catch块中的异常
finally中的异常会覆盖(消灭)前面try或者catch中的异常
finally块仅仅用来释放资源是最合适的
将尽量将所有的return写在函数的最后面,而不是try … catch … finally中。
//catch中的异常被抑制@SuppressWarnings("finally")public static int foo() throws Exception{try {int a = 5/0;return 1;}catch(ArithmeticException amExp) {throw new Exception("我将被忽略,因为下面的finally中使用了return");}finally {return 100;}}//try中的异常被抑制@SuppressWarnings("finally")public static int bar() throws Exception{try {int a = 5/0;return 1;}finally {return 100;}}//............//catch中的异常被抑制@SuppressWarnings("finally")public static int foo() throws Exception{try {int a = 5/0;return 1;}catch(ArithmeticException amExp) {throw new Exception("我将被忽略,因为下面的finally中抛出了新的异常");}finally {throw new Exception("我是finaly中的Exception");}}//try中的异常被抑制@SuppressWarnings("finally")public static int bar() throws Exception{try {int a = 5/0;return 1;}finally {throw new Exception("我是finaly中的Exception");}}
注意事项:
- catch 不能独立于 try 存在。
- 在 try/catch 后面添加 finally 块并非强制性要求的。
- try 代码后不能既没 catch 块也没 finally 块。
- try, catch, finally 块之间不能添加任何代码。
如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明
一个方法可以声明抛出多个(非检查性)异常,多个异常之间用逗号隔开
当子类重写父类的带有 throws声明的函数时,其throws声明的异常必须在父类异常的可控范围内
用throws抛出检查性异常的方法,调用它的方法必须try-catch或者继续throws
在Java中定义了两种类型的异常和错误。
如果要自定义异常类,则扩展Exception类即可,因此这样的自定义异常都属于检查异常(checked exception)。如果要自定义非检查异常,则扩展自RuntimeException。
按照国际惯例,自定义的异常应该总是包含如下的构造函数:
一个无参构造函数
一个带有String参数的构造函数,并传递给父类的构造函数。
一个带有String参数和Throwable参数,并都传递给父类构造函数
一个带有Throwable 参数的构造函数,并传递给父类的构造函数。
下面是IOException类的完整源代码,可以借鉴。
public class IOException extends Exception{static final long serialVersionUID = 7818375828146090155L;public IOException(){super();}public IOException(String message){super(message);}public IOException(String message, Throwable cause){super(message, cause);}public IOException(Throwable cause){super(cause);}}
package com.nl.sx814.wrapper;import org.junit.Test;/*** Created with IntelliJ IDEA 2018.* Description:包装类* Author: 黄昭鸿* Date: 2018-08-14* Time: 16:37*/public class TestWrapper {@Testpublic void test01() {/*** Description:包装类和基本数据类型的互相转换* @author 黄昭鸿* @date 2018/8/15 9:25* @param []* @return void*///基本类型-->包装类//装箱:自动将基本数据类型转换为其对应的包装类.//拆箱:自动将包装类型转换为基本数据类型.int i = 9;//Integer(int) 已经过时了java.net.URLDecoder 中的方法decode(String encodeStr) 这个方法已经过时,应该使用双参数decode(String source, String encode)。//Integer integer=new Integer(i);Integer integer = Integer.valueOf(i);System.out.println(integer);//自动拆箱int ii = integer;//'Float(java.lang.String)' 已经过时了//Float f=new Float("10.9f");Float f = Float.valueOf("10.9f");System.out.println(f);Booleanb1 = Boolean.valueOf("true"),//falseb2 = Boolean.valueOf("sdfghgfd"),b3 = Boolean.FALSE;System.out.println(b1);System.out.println(b2);System.out.println(b3);//引用类型默认值nullBb bb = new Bb();System.out.println(bb.aBoolean);//包装类-->基本数据类型int i1 = integer.intValue();float f2 = f.floatValue();boolean bL = b3.booleanValue();//System.out.println(i1 + "," + f2 + "," + bL + ".");}@Testpublic void test02() {/*** Description: 基本数据类型、包装类与String之间的互相转换** @author 黄昭鸿* @date 2018/8/15 10:14* @param []* @return void*///String --> 基本数据类型、包装类,调用包类的parseXxx(String)方法String str = "996";//只产生一个对象int i1 = Integer.parseInt(str);//会多产生一个对象//int i1 = Integer.valueOf(str.trim()).intValue();//'Boolean(String)' 已经过时了boolean b = Boolean.parseBoolean("true");Integer integer = Integer.parseInt("668");//基本数据类型、包装类 --> String:valueOf()//会产生两个String对象//str=i1+"";//只产生一个对象str = String.valueOf(i1);//str = String.valueOf(b);//str = String.valueOf(integer);//System.out.println(str + "," + i1 + "," + b + "," + integer + ".");}}class Bb {//默认值nullBoolean aBoolean;}
package com.nl.sx815.exception;//import org.junit.Test;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Date;import java.util.InputMismatchException;import java.util.Scanner;/*** Created with IntelliJ IDEA 2018.* Description:Java异常* Exception和Error的直接父类:Throwable* Exception:异常,可处理* Error:错误,程序中不进行处理* Exception有两个主要的子类:IOException 类和 RuntimeException 类* <p>* 方式一(通常用来捕获检查性异常)* try catch自行处理异常--->test07()* 方式二(通常用来抛出非检查性异常)* throws/throw -->test08()** @author : 黄昭鸿* @date : 2018-08-15* Time: 11:10*/public class ExceptionDemo {public static void main(String[] args) {//应用程序没有处理抛出的异常时,会交由JVM来处理这个异常。结果是://当前线程会停止运行,异常触发点后面的代码将得不到运行。//异常栈信息会通过标准错误流输出。//异常发生时,(如果发生的异常没有被被处理)发生异常的语句后面的代码不继续执行ExceptionDemo exceptionDemo = new ExceptionDemo();System.out.println("1..");//ClassCastException(非检查性)exceptionDemo.test01();System.out.println("2..");//ArrayIndexOutOfBoundsException(非检查性)exceptionDemo.test02();System.out.println("3..");//ArithmeticException: / by zero(非检查性)exceptionDemo.test03();System.out.println("4..");//NullPointerException(非检查性)exceptionDemo.test04();System.out.println("5..");//FileNotFoundException检查性异常(方法内部try catch自行处理异常)exceptionDemo.test05();System.out.println("6..");//InputMismatchException输入类型不匹配异常(非检查性)exceptionDemo.test06();System.out.println("7..");//算术异常ArithmeticException(非检查性)exceptionDemo.test07();System.out.println("8..");//用throws抛出检查性异常的方法,调用它的方法必须try-catch或者继续throwstry {//FileNotFoundException,检查性异常exceptionDemo.test08();} catch (IOException e) {e.printStackTrace();}}public void test01() {Object object = new Date();//类型转换异常,ClassCastExceptiontry {String s = (String) object;System.out.println(s);} catch (ClassCastException e) {e.printStackTrace();}//下面语句可正常转换System.out.println(String.valueOf(object));//异常发生时,(如果发生的异常没有被被处理)发生异常的语句后面的代码不继续执行}//非检查性异常,数组下标越界异常ArrayIndexOutOfBoundsExceptionpublic void test02() {try {int[] ints = new int[3];System.out.println(ints[3]);} catch (ArrayIndexOutOfBoundsException e) {e.printStackTrace();}}public void test03() {//非检查性异常,算术异常ArithmeticException: / by zero////异常发生时,(如果发生的异常没有被被处理)发生异常的语句后面的代码不继续执行try {System.out.println(1 / 0);} catch (ArithmeticException e) {e.printStackTrace();}}//空指针异常NullPointerExceptionpublic void test04(){try {P p = new P();p = null;p.toString();} catch (NullPointerException e) {e.printStackTrace();}}//FileNotFoundException检查性异常(编译时异常)public void test05() {try {FileInputStream fileInputStream = new FileInputStream(new File("hello.txt"));int t;while ((t = fileInputStream.read()) != -1) {System.out.println((char) t);}} catch (FileNotFoundException e) {//小范围在前面(子类)e.printStackTrace();} catch (IOException e) {//大范围在后面(父类)e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}//输入类型不匹配异常InputMismatchException(非检查性)public void test06() {Scanner scanner = new Scanner(System.in);try {int i = scanner.nextInt();System.out.println(i);} catch (InputMismatchException e) {System.out.println("出现输入类型不匹配异常");e.printStackTrace();//System.out.println(e.getMessage());//StackTraceElement[] ste=e.getStackTrace();//System.out.println(ste[0]);}}//try catch自行处理异常Exceptionpublic void test07() {try {//算术异常ArithmeticException: / by zeroSystem.out.println(1 / 0);} catch (ArithmeticException e) {e.printStackTrace();} finally {//finally中的return 会覆盖 try 或者catch中的返回值//finally中的return会抑制(消灭)前面try或者catch块中的异常//finally中的异常会覆盖(消灭)前面try或者catch中的异常//finally块仅仅用来释放资源是最合适的//将尽量将所有的return写在函数的最后面,而不是try … catch … finally中。}}public void test08() throws IOException, FileNotFoundException {//FileNotFoundException(系统找不到指定的文件。)FileInputStream fileInputStream = new FileInputStream(new File("hello.txt"));int temp;while ((temp = fileInputStream.read()) != -1) {System.out.println((char) temp);}}}class P {}