1.使用throws声明异常
在有些情况下,一个方法不能处理或者不知道怎么处理异常的时候,可以通过throws向上传递,由调用它的方法来处理,直到main()方法。
public class ExceptionTest {
public static void num(int x)throws ArithmeticException{
int y=100/x;
}
public static void main(String[] args) {
try{
int x=0;
num(x);
}catch (ArithmeticException e){
System.out.println("捕获异常");
e.printStackTrace();
}
}
2.throw语句
在实际编程中,可以使用throw抛出自己的异常。
例如:
public static void num(int x)throws Exception{
if (x>50){
throw new Exception("太老了!");
}
}
public static void main(String[] args) {
int y=80;
try{
num(y);
}catch (Exception e){
System.out.println(y);
System.out.println("原因:"+e.getMessage());
}
}
3.自定义异常
尽管有这么多的异常类,但是有的时候还是需要自己定义一些异常类,来解决一些特殊情况。
自定义异常 的步骤:
1.创建自定义异常类
2.在方法中通过throw抛出异常对象
3.使用try catch处理异常
4.
注意事项
1.try catch fially throw throws 这五个关键字不能单独使用,否则会编译出错;
2.try语句之后可以只使用catch或者只使用finally,catch可以有多个,finally只能有一个,finally必须在最后;
3.对于发生的异常必须使用try catch,或者使用throw,否则编译出错
4.在throw抛出一个异常后,之后的代码不会执行。
5.在try中声明的变量时局部变量,catch,finally中不能使用。
public class Test{
public static String Username="封";
public static String rightKey ="123456";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String str1 = scanner.nextLine();
System.out.println("请输入密码:");
String str2 = scanner.nextLine();
//捕获并且处理异常
try {
login(str1,str2);
}catch (UsernameError usernameError ){
usernameError.printStackTrace();
}catch (KeyError keyError){
keyError.printStackTrace();
}finally {
}
}
//定义一个login方法,在这个方法中抛出异常
public static void login(String name,String key)throws UsernameError,KeyError{
if (!name.equals(Username)){
throw new UsernameError("用户名错误");
}
if (!key.equals(rightKey)){
throw new KeyError("密码错误");
}System.out.println("登陆成功" );
}
}
//定义两个异常类,继承自Exceptioin
class UsernameError extends Exception{
public UsernameError(String name){
super(name);
}
}
class KeyError extends Exception{
public KeyError(String key){
super(key);
}
}