Java 异常抛出详解
发布日期:2021-06-30 15:37:28
浏览次数:2
分类:技术文章
本文共 1572 字,大约阅读时间需要 5 分钟。
package com.day33.test;
import java.io.File;
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method;//异常处理 throws + 异常类型 抛出异常
// 开发中 如何选择 try catch finally 还是throws // 1. 如果父类中被重写的方法 没有 throws方式处理异常 则子类 重写 的方法也不能使用 throws // 如果子类 重写中有异常 必须使用 try catch finally 处理 public class ExceptionTest { public static void main(String[] strings) { try { method2(); } catch (IOException e) { // TODO: handle exception System.out.println(e.getMessage()); } //手动抛出异常处理 Student student =new Student(); try { student.regist(-100); } catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); } } public static void method1() throws FileNotFoundException,IOException { File file =new File("hello.txt"); FileInputStream fileInputStream =new FileInputStream(file); int data=fileInputStream.read(); while (data != -1) { System.out.println((char) data); data=fileInputStream.read(); } fileInputStream.close(); } public static void method2() throws IOException { method1(); } } //手动抛出异常 class Student{ private int id; public void regist(int id) throws Exception { if(id>0) { this.id=id ; }else { // 调用系统异常 // throw new Exception("不支持负数"); //调用 自定义异常 throw new MyException("不支持负数"); } } } // 用户自定义 异常类package com.day33.test;
//自定义异常类
//如何自定义异常类 //1. 继承现有的异常类 : Exception 或者 RuntimeException //2. 提供全局常量 //3. 提供重载构造器 public class MyException extends Exception { static final long serialVersionUID = -3387516993124229948L; public MyException() { } public MyException(String str) { super(str); }}
转载地址:https://jsonll.blog.csdn.net/article/details/110108536 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
关注你微信了!
[***.104.42.241]2024年04月21日 23时00分00秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
python学习笔记
2019-05-01
elasticsearch7.x clusterAPI之pending_tasks
2019-05-01
Ant Task
2019-05-01
如何通过${a${b}}的方式扩展属性名或属性值
2019-05-01
Ant内置任务之antcall
2019-05-01
Ant内置任务之antversion
2019-05-01
Ant内置任务之import
2019-05-01
Ant内置任务之available
2019-05-01
Ant内置任务之basename
2019-05-01
Ant内置任务之bindtargets
2019-05-01
Ant内置任务之buildnumber
2019-05-01
Ant内置任务之dirname
2019-05-01
Ant内置任务之replace
2019-05-01
Ant内置任务之tstamp
2019-05-01
Ant内置任务之whichresource
2019-05-01
Ant内置任务之touch
2019-05-01
Ant内置任务之truncate
2019-05-01
Ant内置任务之sync
2019-05-01
Ant内置任务之symlink
2019-05-01
Ant内置任务之sound
2019-05-01