投掷Java
throws关键字
每当方法中发生异常时,您都需要通过将导致异常的代码包装在try-catch块中来处理它,或者可以使用throws关键字将其抛出/推迟到调用方法中。然后,您需要在调用方法处处理异常。
示例
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionExample{
public static String readFile(String path)throws FileNotFoundException {
String data = null;
Scanner sc = new Scanner(new File("E://test//sample.txt"));
String input;
StringBuffer sb = new StringBuffer();
sb.append(sc.next());
data = sb.toString();
return data;
}
public static void main(String args[]) {
String path = "E://test//sample.txt";
readFile(path);
}
}输出结果
编译时错误
ExceptionExample.java:17: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
readFile(path);
^
1 error要解决此问题,您需要包装调用行或使用throws关键字再次引发异常。
public static void main(String args[]) {
String path = "E://test//sample.txt";
OverridingException obj = new OverridingException();
try {
readFile(path);
}
catch(Exception ex) {
System.out.println("Exception occurred");
}
}throw关键字
您可以使用throw关键字显式引发用户定义的异常或预定义的异常。
用户定义的异常和预定义的异常有两种,每种异常由一个类表示,并继承Throwable类。
要显式抛出异常,您需要实例化它的类并使用throw关键字抛出其对象。
示例
以下Java程序引发NullPointerException
public class ExceptionExample {
public static void main(String[] args) {
System.out.println("Hello");
NullPointerException nullPointer = new NullPointerException();
throw nullPointer;
}
}输出结果
Hello Exception in thread "main" java.lang.NullPointerException at July_set2.ExceptionExample.main(ExceptionExample.java:6)
每当显式抛出异常时,都需要确保带有throw关键字的行是程序的最后一行。这是因为在此之后编写的任何代码都是无法访问的代码,并且如果您在此行下方仍然有代码片段,则会生成编译时错误。
示例
public class ExceptionExample {
public static void main(String[] args) {
System.out.println("Hello");
NullPointerException nullPointer = new NullPointerException();
throw nullPointer;
System.out.println("How are you");
}
}输出结果
编译时错误
D:\>javac ExceptionExample.java
ExceptionExample.java:6: error: unreachable statement
System.out.println("How are you");
^
1 error重新抛出异常
当将异常缓存在catch块中时,可以使用throw关键字(用于抛出异常对象)将其重新抛出。
在处理异常时,您可以抛出相同的异常,而无需将其调整为-
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArithmeticException e) {
throw e;
}或者,将其包装在新的异常中并抛出。当您将缓存的异常包装在另一个异常中并引发异常时,这称为异常链接或异常包装,通过执行此操作,您可以调整异常,并抛出更高级别的异常来维护抽象。
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}示例
在以下Java示例中,我们的演示代码method()可能会引发ArrayIndexOutOfBoundsException和ArithmeticException。我们在两个不同的catch块中捕获了这两个异常。
在catch块中,我们通过包装在较高的异常中来抛出两个异常,而另一个直接抛出。
import java.util.Arrays;
import java.util.Scanner;
public class RethrowExample {
public void demoMethod() {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}
catch(ArithmeticException e) {
throw e;
}
}
public static void main(String [] args) {
new RethrowExample().demoMethod();
}
}输出1
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 0 4 Exception in thread "main" java.lang.ArithmeticException: / by zero at myPackage.RethrowExample.demoMethod(RethrowExample.java:16) at myPackage.RethrowExample.main(RethrowExample.java:25)
输出2
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 124 5 Exception in thread "main" java.lang.IndexOutOfBoundsException at myPackage.RethrowExample.demoMethod(RethrowExample.java:17) at myPackage.RethrowExample.main(RethrowExample.java:23)