当前位置: 首页 > ai >正文

Java基础(异常2)

只要声明了,异常处理就有需求,两种方式:try/catch/finally 向上抛出

一、异常处理_throws

如果一个方法中的语句执行时可能生成某种异常,但是并不能确定如何处理这种异常,则该方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。

不处理,抛给上一层,在方法外处理掉。

package day8;/*
* 异常 - 程序运行过程当中出现的不正常的情况 - 异常类的对象/处理/自定义异常类!!
* 异常体系结构
*   Throwable
*      |--Error 错误
*      |--Exception 异常
*        |--运行时异常 - RuntimeException
*              不需要程序员处理,可以在编程时注意从而避免该类异常的发生
*        |--编译时异常
*              必须写代码进行处理
* 常见的异常/错误
* OutOfMemoryError 内存溢出异常
* StackOverflowError 递归异常
* ArrayIndexOutOfBoundsException 数组下标越界异常
* NullPointerException 空指针异常
* ArithmeticException 算术异常
* ClassCastException 类转换异常
* 异常处理 - 异常类的对象
*  1)通过JVM产生
*  2)由开发人员手动抛出
* 异常处理
*  1、在方法内部解决,自己写代码处理
*   try{
*
*   }catch(NullPointerException 异常类对象的名字1){
*
*   }catch(Exception 异常类对象的名字2){
*
*   }finally{
*
*   }
*   1)try代码块中编写可能出现异常的代码
*   2)catch代码块编写异常处理的代码/捕获的代码
*   3)catch后面的小括号里面声明异常类的对象
*   4)出现异常之后,异常类的对象和哪个“异常类型”匹配就会被哪个catch代码块处理
*   5)异常类型要注意子类在前面,父类在后面 看上面代码(因为父类包含子类的功能)
*   6)finally代码块不管是否出现异常都会被运行,finally代码块不是必需要有的,可以省略
*  2、向上抛出
*   [修饰符] 返回值类型 方法名(参数列表) throws 异常类型1,异常类型2{
*      方法体
*      return 返回值;
* }
* */public class MyTest01 {//OutOfMemoryError 内存溢出异常public static void test1(){int[] arr = new int[1024 * 1024 * 1024];}//StackOverflowError 递归异常public static void test2(){test2();}//ArrayIndexOutOfBoundsException 数组下标越界异常public static void test3(){int[] arr = new int[5];System.out.println(arr[5]);}//NullPointerException 空指针异常public static void test4(){String str = null;System.out.println(str.length());}//ArithmeticException 算术异常public static void test5(){int a = 1 / 0;}//ClassCastException 类转换异常public static void test6(){//Object o = new Object();Object o = new String("111");String s = (String) o;//不能这么转成字符串}public static int test7(int a,int b,String str){int result = 0;try{result = a / b;System.out.println(str.length());}catch (ArithmeticException e){ //e代表被捕获的对象 如果要处理多种异常类//System.out.println("hehe....");e.printStackTrace();}catch (Exception e){//System.out.println("haha....");e.printStackTrace();} finally {System.out.println("finally");}//try/catch运行完还会走下面这个代码return result;}public static int test8(int a,int b,String str) throws Exception{int result = a / b;System.out.println(str.length());return result;}public static void main(String[] args) throws Exception {System.out.println(test8(10, 2,null));/* 不throws 就try {System.out.println(test8(10, 2,null));} catch (Exception e) {e.printStackTrace();}*/}
}

二、异常处理_最佳实践

什么时候需要用上面的两种方式进行处理?

方法(导航到源码)自己声明了向上抛出异常,在调用方法时就要使用上面的方式对异常进行处理。

要么try/catch/finally 要么再向上抛出

package day8;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;public class MyTest02 {public static void main(String[] args)  {String str = "2021-10-11 19:10:20";SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//String --> Date//Date date = sft.parse(str); 要抛出Properties prop = new Properties();//prop.load(new FileInputStream("a.properties")); 也要抛出}
}

三、自定义异常类

Java异常类对象的手动创建,上面的是自动创建。

package day8;/*
* 异常 - 程序运行过程当中出现的不正常的情况 - 异常类的对象/处理/自定义异常类!!
* 异常体系结构
*   Throwable
*      |--Error 错误
*      |--Exception 异常
*        |--运行时异常 - RuntimeException
*              不需要程序员处理,可以在编程时注意从而避免该类异常的发生
*        |--编译时异常
*              必须写代码进行处理
* 常见的异常/错误
* OutOfMemoryError 内存溢出异常
* StackOverflowError 递归异常
* ArrayIndexOutOfBoundsException 数组下标越界异常
* NullPointerException 空指针异常
* ArithmeticException 算术异常
* ClassCastException 类转换异常
* 异常处理 - 异常类的对象
*  1)通过JVM产生
*  2)由开发人员手动抛出
* 异常处理
*  1、在方法内部解决,自己写代码处理
*   try{
*
*   }catch(NullPointerException 异常类对象的名字1){
*
*   }catch(Exception 异常类对象的名字2){
*
*   }finally{
*
*   }
*   1)try代码块中编写可能出现异常的代码
*   2)catch代码块编写异常处理的代码/捕获的代码
*   3)catch后面的小括号里面声明异常类的对象
*   4)出现异常之后,异常类的对象和哪个“异常类型”匹配就会被哪个catch代码块处理
*   5)异常类型要注意子类在前面,父类在后面 看上面代码(因为父类包含子类的功能)
*   6)finally代码块不管是否出现异常都会被运行,finally代码块不是必需要有的,可以省略
*  2、向上抛出
*   [修饰符] 返回值类型 方法名(参数列表) throws 异常类型1,异常类型2{
*      方法体
*      return 返回值;
* }
* */public class MyTest01 {//OutOfMemoryError 内存溢出异常public static void test1(){int[] arr = new int[1024 * 1024 * 1024];}//StackOverflowError 递归异常public static void test2(){test2();}//ArrayIndexOutOfBoundsException 数组下标越界异常public static void test3(){int[] arr = new int[5];System.out.println(arr[5]);}//NullPointerException 空指针异常public static void test4(){String str = null;System.out.println(str.length());}//ArithmeticException 算术异常public static void test5(){int a = 1 / 0;}//ClassCastException 类转换异常public static void test6(){//Object o = new Object();Object o = new String("111");String s = (String) o;//不能这么转成字符串}public static int test7(int a,int b,String str){int result = 0;try{result = a / b;System.out.println(str.length());}catch (ArithmeticException e){ //e代表被捕获的对象 如果要处理多种异常类//System.out.println("hehe....");e.printStackTrace();}catch (Exception e){//System.out.println("haha....");e.printStackTrace();} finally {System.out.println("finally");}//try/catch运行完还会走下面这个代码return result;}public static int test8(int a,int b,String str) throws Exception{int result = a / b;System.out.println(str.length());return result;}public static int test9(int a,int b) throws Exception {if (b == 0){throw new Exception("除数不能为0!!!!!");}return a / b;}public static int test10(int a,int b) throws MyException {if (b == 0){throw new MyException("除数不能为0!!!!!");}return a / b;}public static void main(String[] args)  {/*try {test9(10,0);} catch (Exception e) {e.printStackTrace();}*/try {test10(10,0);} catch (MyException e) {e.printStackTrace();}}
}

http://www.xdnf.cn/news/5391.html

相关文章:

  • MCP:重塑AI交互的通用协议,成为智能应用的基础设施
  • 【js基础笔记] - 包含es6 类的使用
  • C++(9):位运算符进阶版
  • 变换炉设备设计:结构优化与工艺集成
  • 使用vue3-seamless-scroll实现列表自动滚动播放
  • 中空电机在安装垂直轴高速电机后无法动平衡的原因及解决方案
  • 26考研——中央处理器_指令流水线_流水线的冒险与处理 流水线的性能指标 高级流水线技术(5)
  • LintCode第4题-丑数 II
  • java笔记06
  • Three.js + React 实战系列 - 联系方式提交表单区域 Contact 组件✨(表单绑定 + 表单验证)
  • 频率学派和贝叶斯学派置信区间/可信区间的区别
  • spark算子介绍
  • 机器视觉开发教程——C#如何封装海康工业相机SDK调用OpenCV/YOLO/VisionPro/Halcon算法
  • 高精地图数据错误的侵权责任认定与应对之道
  • 【PVE】ProxmoxVE8虚拟机,存储管理(host磁盘扩容,qcow2/vmdk导入vm,vm磁盘导出与迁移等)
  • 数据库分库分表实战指南:从原理到落地
  • 1247. 后缀表达式
  • Compose笔记(二十二)--NavController
  • 数值运算的误差估计
  • DAMA车轮图
  • PyCharm软件下载和配置Python解释器
  • 【英语笔记(八)】介词和冠词的分析;内容涵盖介词构成、常用介词用法、介词短语;使用冠词表示不同的含义:不定冠词、定冠词、零冠词
  • 【Java项目脚手架系列】第六篇:Spring Boot + JPA项目脚手架
  • Git初始化相关配置
  • Vue 跨域解决方案及其原理剖析
  • springboot3+vue3融合项目实战-大事件文章管理系统-更新用户密码
  • 【AI提示词】免疫系统思维专家
  • 英语句型结构
  • ElasticSearch进阶
  • 【C/C++】const关键词及拓展