throws的使用格式:
1.修饰符 返回值类型 方法名(参数列表) throws Exception
2.如要声明多个异常,可以在异常之间用,隔开
3.注意:
(1)如果方法没有在父类中进行声明异常,那么就不能在子类中对其进行继承来声明异常。
(2)throws关键字后面必须是Exception或它的子类
(3)如果方法throw多个异常对象,就要throws多个异常。
(4)如果throw的异常对象有父子关系,那么直接throws父类即可
(5)调用了一个声明抛出异常的方法,我们就必须处理声明的异常。要么使用throws继续声明,最终交给JVM处理,要么使用tyr…catch自行处理。
throws关键字的作用:
当方法内部抛出异常对象时,我们就必须处理这个异常对象,这时就可以使用throws关键字处理异常对象。throws会将对象声明抛出给方法的调用者处理(自己不处理,给别人处理),最终交给JVM处理(中断程序)。
import java.io.FileNotFoundException;
public class ThrowException{
public static void ReadFile(String a) throws FileNotFoundException{
if(!a.equals("C:\\\\a.txt")) {
throw new FileNotFoundException("传递的路径不是C:\\\\a.txt");
}
}
public static void main(String[] args) throws FileNotFoundException {
String a="C:\\\\a.tx";
ReadFile(a);
System.out.println("你好。");//throws中断程序,这一句代码将不能实现
}
}
throw关键字的作用:
可以使用throw关键字在指定的方法内抛出指定的异常
使用格式:
throw new 异常名称(“产生的原因”);
throw new NullPointerException("空指针异常。");
注意:
1.throw 关键字必须写在方法的内部。
public static int getArray(int[] a,int index) {
if(a==null) {
throw new NullPointerException("空指针异常。");
}
if(index<0||index>a.length-1)
{
throw new ArrayIndexOutOfBoundsException("访问数组范围越界。");
}
return a[index];
2.throw关键字后面的对象必须是Excepion或者Exception的子类对象。
3.throw关键字指定的异常对象,我们必须处理它。
(1)如果throw关键字后面创建的是RuntimeException或者是它的子类对象,我们可以不处理,默认交给JVM处理(打印异常对象,中断程序)
public class ThrowException{
public static int getArray(int[] a,int index) {
if(a==null) {
throw new NullPointerException("空指针异常。");
//NullPointerException是RuntimeException的子类,默认交给JVM处理。
}
if(index<0||index>a.length-1)
{
//如果数组的索引越界,就抛出越界异常,告知调用者,传递的索引越界
throw new ArrayIndexOutOfBoundsException("访问数组范围越界。"); //这个也是RuntimeException的子类。
}
return a[index];
}
public static void main(String[] args) {
int a[] = null;
//int[] a = new int[4];
int e = getArray(a,5);
}
}
(2)如果throw关键字后面创建的是编译异常,那么我们就必须处理这个异常,要麽throws(交给调用的它的方法处理),要么try…catch。
import java.io.FileNotFoundException;
public class ThrowException{
public static void ReadFile(String a) throws FileNotFoundException{
if(!a.equals("C:\\\\a.txt")) {
throw new FileNotFoundException("传递的路径不是C:\\\\a.txt");
}
}
public static void main(String[] args) throws FileNotFoundException {
String a="C:\\\\a.tx";
ReadFile(a);
}
}
import java.io.FileNotFoundException;
public class ThrowException{
public static void ReadFile(String a) {
if(!a.equals("C:\\\\a.txt")) {
try{
throw new FileNotFoundException();
}
catch(FileNotFoundException e) {
System.out.println("传递的文件路径不是C:\\\\a.txt");
}
}
}
public static void main(String[] args) {
String a="C:\\\\a.tx";
ReadFile(a);
}
}
总结:
声明抛出的异常,必须处理,要么使用try…catch自行处理,要么继续声明上抛,最终给JVM处理(中断程序运行)。