throws关键字
异常第一种方式 交给别人处理
作用 当方法内部抛出异常对象的时候,那么我们就可以必须处理这个异常对象
可以使用throws关键字处理异常对象,会把异常对象声明抛出给方法的调用者(自己不处理,给别人处理)最终交给JVM处理–>中断处理
使用格式 :在方法声明时使用
修饰符 返回值 方法名(参数列表) throws AAAException,BBBException…{
throw new AAAException(“产生原因”)
throw new BBBException(“产生原因”)
}
注意 1 throws关键字必须写在方法声明出
2 throws 关键字后面声明的异常必须是Exception或者是Exception的子类
3 方法内部如果抛出了多个异常,那么throws后面必须也声明多个异常,如果抛出的异常的对象有子父类关系,那么直接声明父类异常即可
4调用了一个声明抛出异常的方法 我们就必须处理声明的异常 要么继续使用throws声明抛出,交给方法的调用者处理,最终交给JVM
public class demoThrows {
public static void main(String[] args) throws IOException ,FileNotFoundException{
readFile("D:\\");
}
/*
定义一个方法 ,对传递的文件路径进行合法性判定
*/
public static void readFile(String fileName) throws IOException ,FileNotFoundException{
if(!fileName.equals("C:\\a.txt")){
throw new FileNotFoundException("文件的路径有问题");
}
if(fileName.endsWith(".txt")){
throw new IOException("文件格式有问题");
}
}
}
/*
throw 关键字
作用 ;可以用throw关键字在指点的方法中抛出指定的异常
使用格式 : throw new xxxException(“异常产生的原因”)
注意: 1 throw关键字必须写在方法的内部
2 throw 关键字后面new的对象必须是Exception或者Exception的子类对象
throw关键字后面创建的是RuntimeException 或者是RuntimeException的子类,我们可以不处理,默认交给JVM打印
throw 关键字后面创建额是编译器异常(写代码报的错误)我们必须处理这个异常要么throws 要么try canth()
*/
Objects.requireNonNull() 合法性判定 是否为null
public static void main(String[] args) {
/* int [] arr=new int[3];
getElement(arr,3);*/
method(null);
}
public static int getElement(int [] arr,int index){
if(arr==null){
throw new NullPointerException("数组为空");
}
if(index>arr.length ||index<0){
throw new ArrayIndexOutOfBoundsException("数组的索引越界");
}
int ele=arr[index];
return ele;
}
/*
Objects.requireNonNull() 合法性判定 是否为null
*/
public static void method(Object obj) {
Objects.requireNonNull(obj);
Objects.requireNonNull(obj,"NullPointerException");
}
try catch
一个try多个catch注意事项:
catch里面定义的异常变量,如果有子父类关系,子类的异常必须写在上面 ,否则就会报错
****Throwable 定义3个异常处理的方法
String getMessage() 返回throwable的简短描述
String toString() 返回throwable的详细信息
void printStackTrace(); JVM打印异常信息最全的信息**
/*finally不能单独使用 ,无论发不发生异常 都会执行,一般用于资源释放**
public class DemoTryCatch {
public static void main(String[] args) {
try {
readFile("D:\\");
} catch (IOException e) {
/*
Throwable 定义3个异常处理的方法
String getMessage() 返回throwable的简短描述
String toString() 返回throwable的详细信息
void printStackTrace(); JVM打印异常信息最全的信息
*/
e.printStackTrace();
System.out.println( e.getMessage());
System.out.println( e.toString());
}
finally {
//无论发不发生异常 都会执行,一般用于资源释放
/*finally不能单独使用
*/
System.out.println("无论发不发生异常 都会执行");
}
}
/*
定义一个方法 ,对传递的文件路径进行合法性判定
*/
public static void readFile(String fileName) throws IOException ,FileNotFoundException{
if(!fileName.equals("C:\\a.txt")){
throw new FileNotFoundException("文件的路径有问题");
}
if(fileName.endsWith(".txt")){
throw new IOException("文件格式有问题");
}
}
}