[关闭]
@nextleaf 2018-08-16T03:48:02.000000Z 字数 11199 阅读 743

2018-08-15 工作日志

Java 包装类 异常 转换 工作日志


2.4 抽象类和接口的区别

1). 抽象类中的方法可以有方法体,就是能实现方法的具体功能,但是接口中的方法不行。
2). 抽象类中的成员变量可以是各种类型的,而接口中的成员变量只能是 public static final 类型的。
3). 接口中不能含有静态代码块以及静态方法(用 static 修饰的方法),而抽象类是可以有静态代码块和静态方法。
4). 一个类只能继承一个抽象类,而一个类却可以实现多个接口。


包装类

基本数据类型及对应的包装类
基本数据类型 对应的包装类
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean

包装类和基本数据类型的互相转换

基本类型-->包装类

  1. //装箱:自动将基本数据类型转换为其对应的包装类.
  2. //拆箱:自动将包装类型转换为基本数据类型.
  3. int i = 9;
  4. //Integer(int) 已经过时了java.net.URLDecoder 中的方法decode(String encodeStr) 这个方法已经过时,应该使用双参数decode(String source, String encode)。
  5. //Integer integer=new Integer(i);
  6. Integer integer = Integer.valueOf(i);
  7. System.out.println(integer);
  8. //自动拆箱
  9. int ii = integer;
  10. //'Float(java.lang.String)' 已经过时了
  11. //Float f=new Float("10.9f");
  12. Float f = Float.valueOf("10.9f");
  13. System.out.println(f);
  14. Boolean
  15. b1 = Boolean.valueOf("true"),
  16. //false
  17. b2 = Boolean.valueOf("sdfghgfd"),
  18. b3 = Boolean.FALSE;
  19. System.out.println(b1);
  20. System.out.println(b2);
  21. System.out.println(b3);
  22. //引用类型默认值null
  23. Bb bb = new Bb();
  24. System.out.println(bb.aBoolean);

包装类-->基本数据类型

  1. int i1 = integer.intValue();
  2. float f2 = f.floatValue();
  3. boolean bL = b3.booleanValue();

基本数据类型、包装类与String之间的互相转换

String --> 基本数据类型、包装类:调用包类的parseXxx(String)方法

  1. String str = "996";
  2. //只产生一个对象
  3. int i1 = Integer.parseInt(str);
  4. //会多产生一个对象
  5. int i1 = Integer.valueOf(str.trim()).intValue();
  6. //'new Boolean(String)' 已经过时了
  7. boolean b = Boolean.parseBoolean("true");
  8. Integer integer = Integer.parseInt("668");

基本数据类型、包装类 --> String:String.valueOf()

  1. //会产生两个String对象
  2. str=i1+"";
  3. //只产生一个对象
  4. str = String.valueOf(i1);

异常

异常发生的原因有很多,通常包含以下几大类:
1. 用户输入了非法数据。
2. 要打开的文件不存在。
3. 网络通信时连接中断,或者JVM内存溢出。

掌握以下三种类型的异常:

  1. 检查性异常:
    最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略
  2. 运行时异常:
    运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略
  3. 错误:
    错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。

注:

应用程序没有处理抛出的异常时,会交由JVM来处理这个异常。结果是:
当前线程会停止运行,异常触发点后面的代码将得不到运行。
异常栈信息会通过标准错误流输出。

Exception 类的层次

Exception 类的层次

Java 内置异常类

下面的表中列出了 Java 定义在 java.lang 包中的检查性异常类

异常 描述
ClassNotFoundException 应用程序试图加载类时,找不到相应的类,抛出该异常。
CloneNotSupportedException 当调用 Object 类中的 clone 方法克隆对象,但该对象的类无法实现 Cloneable 接口时,抛出该异常。
IllegalAccessException 拒绝访问一个类的时候,抛出该异常。
InstantiationException 当试图使用 Class 类中的 newInstance 方法创建一个类的实例,而指定的类对象因为是一个接口或是一个抽象类而无法实例化时,抛出该异常。
InterruptedException 一个线程被另一个线程中断,抛出该异常。
NoSuchFieldException 请求的变量不存在
NoSuchMethodException 请求的方法不存在

下面的表中列出了 Java 的非检查性异常

异常 描述
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类。

Throwable 类的主要方法

对异常对象的处理(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 catch捕获块

(通常用来捕获检查性异常)

  1. try{
  2. // 程序代码1
  3. }catch(异常类型1 异常的对象名1){
  4. // 程序代码2
  5. }catch(异常类型2 异常的对象名2){
  6. // 程序代码3
  7. }catch(异常类型2 异常的对象名2){
  8. // 程序代码4
  9. }

如果try代码中发生异常,异常被抛给第一个 catch 块(如果发生的异常包含在 catch 块中,异常会被传递到该 catch 块)。
如果抛出异常的数据类型与 "异常类型1" 匹配,它在这里就会被捕获,执行该catch块,后面的catch块将被忽略,
如果不匹配,它会被传递给第二个 catch 块,如此,直到异常被捕获或者通过所有的 catch 块。
如果没有catch块匹配,则先执行finally。
如果多个catch中的"异常类型"是“包含”关系,要将子类写在前面父类写在后面。

finally关键字

无论是否发生异常,finally 代码块中的代码总会被执行
在 try块中即便有return,break,continue等改变执行流的语句,finally也会执行
finally中的return 会覆盖 try 或者catch中的返回值
finally中的return会抑制(消灭)前面try或者catch块中的异常
finally中的异常会覆盖(消灭)前面try或者catch中的异常
finally块仅仅用来释放资源是最合适的
将尽量将所有的return写在函数的最后面,而不是try … catch … finally中。

  1. //catch中的异常被抑制
  2. @SuppressWarnings("finally")
  3. public static int foo() throws Exception
  4. {
  5. try {
  6. int a = 5/0;
  7. return 1;
  8. }catch(ArithmeticException amExp) {
  9. throw new Exception("我将被忽略,因为下面的finally中使用了return");
  10. }finally {
  11. return 100;
  12. }
  13. }
  14. //try中的异常被抑制
  15. @SuppressWarnings("finally")
  16. public static int bar() throws Exception
  17. {
  18. try {
  19. int a = 5/0;
  20. return 1;
  21. }finally {
  22. return 100;
  23. }
  24. }
  25. //............
  26. //catch中的异常被抑制
  27. @SuppressWarnings("finally")
  28. public static int foo() throws Exception
  29. {
  30. try {
  31. int a = 5/0;
  32. return 1;
  33. }catch(ArithmeticException amExp) {
  34. throw new Exception("我将被忽略,因为下面的finally中抛出了新的异常");
  35. }finally {
  36. throw new Exception("我是finaly中的Exception");
  37. }
  38. }
  39. //try中的异常被抑制
  40. @SuppressWarnings("finally")
  41. public static int bar() throws Exception
  42. {
  43. try {
  44. int a = 5/0;
  45. return 1;
  46. }finally {
  47. throw new Exception("我是finaly中的Exception");
  48. }
  49. }

注意事项:

  • catch 不能独立于 try 存在。
  • 在 try/catch 后面添加 finally 块并非强制性要求的。
  • try 代码后不能既没 catch 块也没 finally 块。
  • try, catch, finally 块之间不能添加任何代码。

throws/throw 关键字

如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明
一个方法可以声明抛出多个(非检查性)异常,多个异常之间用逗号隔开
当子类重写父类的带有 throws声明的函数时,其throws声明的异常必须在父类异常的可控范围内
用throws抛出检查性异常的方法,调用它的方法必须try-catch或者继续throws

通用异常

在Java中定义了两种类型的异常和错误。

自定义异常

如果要自定义异常类,则扩展Exception类即可,因此这样的自定义异常都属于检查异常(checked exception)。如果要自定义非检查异常,则扩展自RuntimeException。

按照国际惯例,自定义的异常应该总是包含如下的构造函数:

一个无参构造函数
一个带有String参数的构造函数,并传递给父类的构造函数。
一个带有String参数和Throwable参数,并都传递给父类构造函数
一个带有Throwable 参数的构造函数,并传递给父类的构造函数。
下面是IOException类的完整源代码,可以借鉴。

  1. public class IOException extends Exception
  2. {
  3. static final long serialVersionUID = 7818375828146090155L;
  4. public IOException()
  5. {
  6. super();
  7. }
  8. public IOException(String message)
  9. {
  10. super(message);
  11. }
  12. public IOException(String message, Throwable cause)
  13. {
  14. super(message, cause);
  15. }
  16. public IOException(Throwable cause)
  17. {
  18. super(cause);
  19. }
  20. }

包装类TestWrapper.java

  1. package com.nl.sx814.wrapper;
  2. import org.junit.Test;
  3. /**
  4. * Created with IntelliJ IDEA 2018.
  5. * Description:包装类
  6. * Author: 黄昭鸿
  7. * Date: 2018-08-14
  8. * Time: 16:37
  9. */
  10. public class TestWrapper {
  11. @Test
  12. public void test01() {
  13. /**
  14. * Description:包装类和基本数据类型的互相转换
  15. * @author 黄昭鸿
  16. * @date 2018/8/15 9:25
  17. * @param []
  18. * @return void
  19. */
  20. //基本类型-->包装类
  21. //装箱:自动将基本数据类型转换为其对应的包装类.
  22. //拆箱:自动将包装类型转换为基本数据类型.
  23. int i = 9;
  24. //Integer(int) 已经过时了java.net.URLDecoder 中的方法decode(String encodeStr) 这个方法已经过时,应该使用双参数decode(String source, String encode)。
  25. //Integer integer=new Integer(i);
  26. Integer integer = Integer.valueOf(i);
  27. System.out.println(integer);
  28. //自动拆箱
  29. int ii = integer;
  30. //'Float(java.lang.String)' 已经过时了
  31. //Float f=new Float("10.9f");
  32. Float f = Float.valueOf("10.9f");
  33. System.out.println(f);
  34. Boolean
  35. b1 = Boolean.valueOf("true"),
  36. //false
  37. b2 = Boolean.valueOf("sdfghgfd"),
  38. b3 = Boolean.FALSE;
  39. System.out.println(b1);
  40. System.out.println(b2);
  41. System.out.println(b3);
  42. //引用类型默认值null
  43. Bb bb = new Bb();
  44. System.out.println(bb.aBoolean);
  45. //包装类-->基本数据类型
  46. int i1 = integer.intValue();
  47. float f2 = f.floatValue();
  48. boolean bL = b3.booleanValue();
  49. //System.out.println(i1 + "," + f2 + "," + bL + ".");
  50. }
  51. @Test
  52. public void test02() {
  53. /**
  54. * Description: 基本数据类型、包装类与String之间的互相转换
  55. *
  56. * @author 黄昭鸿
  57. * @date 2018/8/15 10:14
  58. * @param []
  59. * @return void
  60. */
  61. //String --> 基本数据类型、包装类,调用包类的parseXxx(String)方法
  62. String str = "996";
  63. //只产生一个对象
  64. int i1 = Integer.parseInt(str);
  65. //会多产生一个对象
  66. //int i1 = Integer.valueOf(str.trim()).intValue();
  67. //'Boolean(String)' 已经过时了
  68. boolean b = Boolean.parseBoolean("true");
  69. Integer integer = Integer.parseInt("668");
  70. //基本数据类型、包装类 --> String:valueOf()
  71. //会产生两个String对象
  72. //str=i1+"";
  73. //只产生一个对象
  74. str = String.valueOf(i1);
  75. //str = String.valueOf(b);
  76. //str = String.valueOf(integer);
  77. //System.out.println(str + "," + i1 + "," + b + "," + integer + ".");
  78. }
  79. }
  80. class Bb {
  81. //默认值null
  82. Boolean aBoolean;
  83. }

Java异常ExceptionDemo.java

  1. package com.nl.sx815.exception;
  2. //import org.junit.Test;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.util.Date;
  8. import java.util.InputMismatchException;
  9. import java.util.Scanner;
  10. /**
  11. * Created with IntelliJ IDEA 2018.
  12. * Description:Java异常
  13. * Exception和Error的直接父类:Throwable
  14. * Exception:异常,可处理
  15. * Error:错误,程序中不进行处理
  16. * Exception有两个主要的子类:IOException 类和 RuntimeException 类
  17. * <p>
  18. * 方式一(通常用来捕获检查性异常)
  19. * try catch自行处理异常--->test07()
  20. * 方式二(通常用来抛出非检查性异常)
  21. * throws/throw -->test08()
  22. *
  23. * @author : 黄昭鸿
  24. * @date : 2018-08-15
  25. * Time: 11:10
  26. */
  27. public class ExceptionDemo {
  28. public static void main(String[] args) {
  29. //应用程序没有处理抛出的异常时,会交由JVM来处理这个异常。结果是:
  30. //当前线程会停止运行,异常触发点后面的代码将得不到运行。
  31. //异常栈信息会通过标准错误流输出。
  32. //异常发生时,(如果发生的异常没有被被处理)发生异常的语句后面的代码不继续执行
  33. ExceptionDemo exceptionDemo = new ExceptionDemo();
  34. System.out.println("1..");
  35. //ClassCastException(非检查性)
  36. exceptionDemo.test01();System.out.println("2..");
  37. //ArrayIndexOutOfBoundsException(非检查性)
  38. exceptionDemo.test02();System.out.println("3..");
  39. //ArithmeticException: / by zero(非检查性)
  40. exceptionDemo.test03();System.out.println("4..");
  41. //NullPointerException(非检查性)
  42. exceptionDemo.test04();System.out.println("5..");
  43. //FileNotFoundException检查性异常(方法内部try catch自行处理异常)
  44. exceptionDemo.test05();System.out.println("6..");
  45. //InputMismatchException输入类型不匹配异常(非检查性)
  46. exceptionDemo.test06();System.out.println("7..");
  47. //算术异常ArithmeticException(非检查性)
  48. exceptionDemo.test07();System.out.println("8..");
  49. //用throws抛出检查性异常的方法,调用它的方法必须try-catch或者继续throws
  50. try {
  51. //FileNotFoundException,检查性异常
  52. exceptionDemo.test08();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. public void test01() {
  58. Object object = new Date();
  59. //类型转换异常,ClassCastException
  60. try {
  61. String s = (String) object;
  62. System.out.println(s);
  63. } catch (ClassCastException e) {
  64. e.printStackTrace();
  65. }
  66. //下面语句可正常转换
  67. System.out.println(String.valueOf(object));
  68. //异常发生时,(如果发生的异常没有被被处理)发生异常的语句后面的代码不继续执行
  69. }
  70. //非检查性异常,数组下标越界异常ArrayIndexOutOfBoundsException
  71. public void test02() {
  72. try {
  73. int[] ints = new int[3];
  74. System.out.println(ints[3]);
  75. } catch (ArrayIndexOutOfBoundsException e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. public void test03() {
  80. //非检查性异常,算术异常ArithmeticException: / by zero
  81. ////异常发生时,(如果发生的异常没有被被处理)发生异常的语句后面的代码不继续执行
  82. try {
  83. System.out.println(1 / 0);
  84. } catch (ArithmeticException e) {
  85. e.printStackTrace();
  86. }
  87. }
  88. //空指针异常NullPointerException
  89. public void test04(){
  90. try {
  91. P p = new P();
  92. p = null;
  93. p.toString();
  94. } catch (NullPointerException e) {
  95. e.printStackTrace();
  96. }
  97. }
  98. //FileNotFoundException检查性异常(编译时异常)
  99. public void test05() {
  100. try {
  101. FileInputStream fileInputStream = new FileInputStream(new File("hello.txt"));
  102. int t;
  103. while ((t = fileInputStream.read()) != -1) {
  104. System.out.println((char) t);
  105. }
  106. } catch (FileNotFoundException e) {
  107. //小范围在前面(子类)
  108. e.printStackTrace();
  109. } catch (IOException e) {
  110. //大范围在后面(父类)
  111. e.printStackTrace();
  112. } catch (Exception e) {
  113. e.printStackTrace();
  114. }
  115. }
  116. //输入类型不匹配异常InputMismatchException(非检查性)
  117. public void test06() {
  118. Scanner scanner = new Scanner(System.in);
  119. try {
  120. int i = scanner.nextInt();
  121. System.out.println(i);
  122. } catch (InputMismatchException e) {
  123. System.out.println("出现输入类型不匹配异常");
  124. e.printStackTrace();
  125. //System.out.println(e.getMessage());
  126. //StackTraceElement[] ste=e.getStackTrace();
  127. //System.out.println(ste[0]);
  128. }
  129. }
  130. //try catch自行处理异常Exception
  131. public void test07() {
  132. try {
  133. //算术异常ArithmeticException: / by zero
  134. System.out.println(1 / 0);
  135. } catch (ArithmeticException e) {
  136. e.printStackTrace();
  137. } finally {
  138. //finally中的return 会覆盖 try 或者catch中的返回值
  139. //finally中的return会抑制(消灭)前面try或者catch块中的异常
  140. //finally中的异常会覆盖(消灭)前面try或者catch中的异常
  141. //finally块仅仅用来释放资源是最合适的
  142. //将尽量将所有的return写在函数的最后面,而不是try … catch … finally中。
  143. }
  144. }
  145. public void test08() throws IOException, FileNotFoundException {
  146. //FileNotFoundException(系统找不到指定的文件。)
  147. FileInputStream fileInputStream = new FileInputStream(new File("hello.txt"));
  148. int temp;
  149. while ((temp = fileInputStream.read()) != -1) {
  150. System.out.println((char) temp);
  151. }
  152. }
  153. }
  154. class P {}
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注