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);
}
}Java 异常抛出详解
原创
©著作权归作者所有:来自51CTO博客作者json____的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
java 有错抛出异常 java抛出异常代码
异常的使用概述异常及时Java程序在运行的过程中出行的错误异常分类 JVM是如何处理异常的main方法遇到这种问题有两种处理异常的方式 a:自己将问题处理,然后运行 b:没有针对处理方式,就会交给main方法的JVM去处理 c:JVM里面有一个默认的异常处理机制,将异常的名称,信息打印在控制台,并停止程序运行。try抛出异常的三种方式 try...catch tr
java 有错抛出异常 java抛出异常代码 为什么子类不能抛出大于父类的方法 System 抛出异常
















