try{可能出现异常的代码}catch(异常类名 变量名){异常的处理代码;}
编译时异常:必须显示处理,否则程序就会发生错误,无法通过编译。
运行时异常:无需显示处理,也可以和编译时异常一样处理。
编译时异常可以使用try..,catch方式,也可以使用throws异常类名;方式。


throws方式谁调用谁处理
throws:用在方法声明后面,跟的时异常类名,表示抛出异常,由该方法的调用者来处理。表示出现异常的一种可能行,并不一定会发生这些异常。
throw:用在方法体内,跟的是异常对象名,表示抛出异常,由方法体内的语句处理。执行则一定抛出异常。

1
2
3
4
5
6
7
8
9
package 异常;

import javax.annotation.processing.Messager;

public class ScoreException extends Exception{
public ScoreException(String message) {
super(message);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

package 异常;

import java.util.Scanner;



public class Test {
public void checkTest(int score) throws ScoreException {
if(score<0||score>100) {
String message="分数不能小于0大于100";
throw new ScoreException(message);
}else {
System.out.println("正确");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test t=new Test();
Scanner sc=new Scanner(System.in);
System.out.println("请输入分数:");
int score=sc.nextInt();
try {
t.checkTest(score);
} catch (ScoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
1
2
3
4
5
6

请输入分数:
111
异常.ScoreException: 分数不能小于0大于100
at 异常.Test.checkTest(Test.java:11)
at 异常.Test.main(Test.java:23)