1、格式
ArithmetricException("")
try(){
throw(ArithmetricException("");
}catch(){
//输出的异常捕获错误
}
2、举个🌰
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数字");
int firstNum = sc.nextInt();
System.out.println("请输入第二个数字");
int secondNum =sc.nextInt();
try {
if (secondNum==0)
//可缺省
// throw new ArithmeticException("除数不能为0");
System.out.println("Result:"+"number1"+"/"+"number2"+"="+firstNum/secondNum);
}catch (ArithmeticException e){
System.out.println("Excption:error,除数不能为0");
}
System.out.println("相除的结果是:");
}
3、常用的三个异常类型
ArithmeticException();
FileNotFoundException();
InputMismatchException();
所有异常类的根是:Throwable
异常类的三种主要类型:
1、系统错误:是由java虚拟机抛出的,用Error 类表示;描述的是内部系统错误;几乎很少发生
Error 类的子类:(免检异常)
LinkageError 、VirtualMachineError;
2、异常(exception)
用Exception类表示的,它描述的是由程序和外部环境引起的错误,这些错误能被程序捕获和处理;
Exception的子类:(必检异常)
ClassNotfoundException、IOException;
3、运行时异常(runtime exception)(免检异常)
是用RunTimeException 类表示的,描述的是程序设计错误,例如:错误的类型转换,访问一个数组越界或者树枝错误,运行时异常通常都是由Java虚拟机抛出的。
RunTimeException的子类:
ArithmeticException
NullPointerException
IndexOutOfBoundsException
IllegalArgumentException
4、方法使用异常捕获的声明
public void myMethod () throws Exception1,Exception2,Exception3...
5、抛出异常
IllegalArgumentException ex = new IllegalArgumentException("wrong ");
throw(ex);
或者
throw new IllegalArgumentException("wrong ");
⚠️注意:声明异常的关键字是throws,抛出异常的关键字是throw;
6、捕获异常
try{
statement;
}
catch(Exception1 ex){
}
catch(Exception2 ex){
}
7、例子
异常方法位置打印
public static void main(String[] args) {
int sum = sum(new int[]{1,2,3,4,5});
try {
System.out.println(sum);
}
catch (Exception ex){
ex.printStackTrace();;
System.out.println("\n"+ex.getMessage());
System.out.println("\n"+ex.toString());
System.out.println("\n trace Info Obained from getStackTrace");
StackTraceElement [] traceElements = ex.getStackTrace();
for (int i = 0; i
System.out.println("method:"+traceElements[i].getMethodName());
System.out.println("\n ClassName"+traceElements[i].getClassName());
System.out.println("\n 行数"+traceElements[i].getLineNumber());
}
}
}
private static int sum(int [] sumArr){
int result = 0;
//这里设置一个错误,用于测试抛出异常
for (int i = 0; i <=sumArr.length; i++) {
result = result+sumArr[i];
}
return result;
}
8、Finally 语句
用法:不论程序是否出现异常或者是否被捕获,都希望执行某些代码;
例子:I/O程序设计,用于最后关闭文件;
public static void main(String[] args) {
//定义局部变量
java.io.PrintWriter outPut = null;
try{
outPut = new java.io.PrintWriter("text.txt");
outPut.println("welcome to java");
}
catch (java.io.IOException ex){
System.out.println("error");
ex.getStackTrace();
}
finally {
if (outPut!=null)
outPut.close();
System.out.println("execute the finally statement");
}
System.out.println("end of program");
}