异常出现,程序变得强大,异常是处理错误的机制
1. 用try...catch处理异常
处理程序员控制和用户输入有误的情况
举例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a,b,c;
Scanner sc = new Scanner (System.in );
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.printf("余数是"+c);
}
}
如果输入aa会出现报错
aa
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.main(Main.java:9)
或者被除数为0时会出现
10
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:11)
此时可以用到try...catch
try{
有可能出现问题的语句
}
catch(Exception e){
出现问题的处理语句
}
增加语句
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
int a,b,c;
Scanner sc = new Scanner (System.in );
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.printf("余数是"+c);
}
catch(Exception e) {
System.out.printf("出现异常");
}
}
}
输出结果
100
0
出现异常
werwf
出现异常
拓展:Exception e 异常的分类
2. 用throws处理异常
抛给上一级处理,如果不行再向上一级,最后交个虚拟机处理,虚拟机终止
一般处理无法避免和处理的异常
举例:
Main类
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LeiA aa= new LeiA();
try{
aa.a();
}
catch(Exception e){
System.out.printf("出现异常");
}
}
}
LeiA类
import java.util.Scanner;
public class LeiA {
void a (){
int a,b,c;
Scanner sc = new Scanner (System.in);
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.printf("余数是"+c);
}
}
增加throws
Main类
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
LeiA aa= new LeiA();
// try{
aa.a();
// }
// catch(Exception e){
System.out.printf("出现异常");
// }
}
}
LeiA类
import java.util.Scanner;
public class LeiA {
void a ()throws Exception
{
int a,b,c;
Scanner sc = new Scanner (System.in);
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.printf("余数是"+c);
}
}
结果
aa
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at LeiA.a(LeiA.java:8)
at Main.main(Main.java:9)
3. Finally
Finally起到异常处理出口的作用,用在try...catch语句最后,无论catch是否执行,Finally都被执行
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
int a,b,c;
Scanner sc = new Scanner (System.in);
try{
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.printf("余数是"+c);
}
catch(Exception e){
System.out.printf("出现异常");
}
finally {
System.out.printf("无论怎样都出现");
}
}
}
运行结果
aa
出现异常无论怎样都出现
网友评论