异常体系结构

偏执的太偏执、 2022-09-05 05:30 270阅读 0赞

常见异常

异常体系结构

java.lang.Throwable
|——-java.lang.Error:一般不编写针对性的代码进行处理
|——-java.lang.Exception:可以进行异常的处理
|———编译时异常(checked)
|——-IOException
|——-FileNotFoundException
|——-ClassNotFoundException
|———运行时异常(unchecked,RuntimeException)
|——-NullPointerException
|——-ArrayIndexOutOfBoundsException
|——-ClassCastException
|——-NumberFormatException
|——-InputMismatchException
|——-ArithmeticException

  1. package com.atguigu.java1;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.util.Date;
  5. import java.util.Scanner;
  6. import org.junit.Test;
  7. public class ExceptionTest {
  8. //******************以下是编译时异常***************************
  9. @Test
  10. public void test7(){
  11. // File file = new File("hello.txt");
  12. // FileInputStream fis = new FileInputStream(file);
  13. //
  14. // int data = fis.read();
  15. // while(data != -1){
  16. // System.out.print((char)data);
  17. // data = fis.read();
  18. // }
  19. //
  20. // fis.close();
  21. }
  22. //******************以下是运行时异常***************************
  23. //ArithmeticException
  24. @Test
  25. public void test6(){
  26. int a = 10;
  27. int b = 0;
  28. System.out.println(a / b);
  29. }
  30. //InputMismatchException
  31. @Test
  32. public void test5(){
  33. Scanner scanner = new Scanner(System.in);
  34. int score = scanner.nextInt();
  35. System.out.println(score);
  36. scanner.close();
  37. }
  38. //NumberFormatException
  39. @Test
  40. public void test4(){
  41. String str = "123";
  42. str = "abc";
  43. int num = Integer.parseInt(str);
  44. }
  45. //ClassCastException
  46. @Test
  47. public void test3(){
  48. Object obj = new Date();
  49. String str = (String)obj;
  50. }
  51. //IndexOutOfBoundsException
  52. @Test
  53. public void test2(){
  54. //ArrayIndexOutOfBoundsException
  55. // int[] arr = new int[10];
  56. // System.out.println(arr[10]);
  57. //StringIndexOutOfBoundsException
  58. String str = "abc";
  59. System.out.println(str.charAt(3));
  60. }
  61. //NullPointerException
  62. @Test
  63. public void test1(){
  64. // int[] arr = null;
  65. // System.out.println(arr[3]);
  66. String str = "abc";
  67. str = null;
  68. System.out.println(str.charAt(0));
  69. }
  70. }

发表评论

表情:
评论列表 (有 0 条评论,270人围观)

还没有评论,来说两句吧...

相关阅读

    相关 异常体系

    异常 异常一般指不期而至的各种状况,如:文件不存在、空指针、非法参数等。 异常是一个事件,发生在程序运行期间,干扰了正常的指令流程。 Java 中使用 Throw