Java throws关键字
Java throws关键字用于声明异常。它为程序员提供了可能发生异常的信息,因此最好提供异常处理代码,以便可以维持正常流程。
异常处理主要用于处理检查到的异常。例外。如果发生任何未检查的异常(例如NullPointerException),则程序员会犯错,即在使用代码之前他没有执行检查。
Java throws语法
return_type method_name() throws exception_class_name{
//method code}
应声明哪个异常
Ans)仅检查异常,因为:
未经检查的异常: 在您的控制之下,请更正您的代码。
错误: 超出您的控制范围,例如如果发生VirtualMachineError或StackOverflowError,您将无法执行任何操作。
Java throws关键字的优势
Now Checked Exception可以传播(在调用堆栈中转发)。
它将信息提供给调用者有关异常的方法。
Java throws示例
让我们看一下Java throws子句的示例,该子句描述了可以通过throws关键字传播已检查的异常。
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");
//checked exception }
void n()throws IOException{
m();
}
void p(){
try{
n();
}
catch(Exception e){
System.out.println("exception handled");
}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
输出:
exception handlednormal flow...
规则: 如果要调用的方法声明了异常,则必须捕获或声明该异常。
有两种情况:
案例1: 您捕获了异常,即使用try/catch处理异常。
案例2: 您声明异常,即使用该方法指定throws。
案例1: 您可以处理异常
如果您处理了异常,则无论程序是否发生异常,都将很好地执行代码。
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}
catch(Exception e){
System.out.println("exception handled");
}
System.out.println("normal flow...");
}
}
Output:exception handled normal flow...
案例2: 您声明了例外情况
A)如果您声明了异常,则如果未发生异常,则代码将正常执行。
B)如果在发生异常时声明异常,则在运行时将引发异常,因为throws无法处理该异常。
A)如果没有发生异常
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{
//declare exception M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:device operation performed normal flow...
B)如果发生异常
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{
//declare exception M m=new M();
m.method();
System.out.println("normal flow...");
}
}