是否可以在Java中不使用“ throws Exception”而引发异常?
当Java中发生异常时,程序异常终止,并且导致异常的行之后的代码也不会执行。
要解决此问题,您需要将导致异常的代码包装在trycatchot中,然后使用throws子句抛出异常。如果使用throws子句引发异常,它将被p[推迟到调用行,即
示例
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不使用抛出
当将异常缓存在catch块中时,可以使用throw关键字(用于抛出异常对象)将其重新抛出。如果重新抛出该异常,则就像在throws子句的情况下一样,此异常将在调用当前异常的方法中在处生成。
示例
在以下Java示例中,我们在demomethod()中的代码可能会引发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)