错误:未报告的异常错误,必须对其进行捕获或声明以便抛出
出现错误:是因为没有对异常进行捕获或声明
首先说一下Java 中throws的作用:
假如函数部分有不合法的异常,例如分母为0:
import java.util.Scanner;
public class Helloexcept{
public static void main(String[] args)throws Exception{
int c=1/0;
System.out.println(c);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
编译之后,将会抛出异常:
在Java中,根据错误性质将运行错误分为两类:错误和异常。
在Java程序的执行过程中,如果出现了异常事件,就会生成一个异常对象。生成的异常对象将传递Java运行时系统,这一异常的产生和提交过程称为抛弃(throw)异常。当Java运行时系统得到一个异常对象时,它将会沿着方法的调用栈逐层回溯,寻找处理这一异常的代码。找到能够处理这类异常的方法后,运行时系统把当前异常对象交给这个方法进行处理,这一过程称为捕获(catch)异常。
解决:
方法一:
即在main函数的后面加入throws Exception的异常捕获
import java.util.Scanner;
public class ReadData{
public static void main(String[] args)throws Exception{
java.io.File file =new java.io.File("xixi.txt");
Scanner input=new Scanner(file);
while(input.hasNext()){
String firstname=input.next();
String mi=input.next();
String lastname=input.nextt();
int score=input.nextInt();
System.out.println(firstname+" "+mi+" "+lastname+" "+score);
}
input.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
方法二:
利用try,catch
import java.util.Scanner;
public class Wrong2343{
public static void main(String[] args){
int c;
try{
c=1/0;
}
catch(Exception e){
System.out.println("Wrong!");
}
System.out.println("Haha!");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
需要注意,如果写Java的类名(文件名)带有Exception时,会出现这样的问题: