try catch作用是抓取异常,
快速添加方式:选中部分需要异常抓取的块,右击鼠标,鼠标放在source with 即可看到 try catch 块
package a13;
import java.util.Scanner;
public class Ouotient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a,b;
a = input.nextInt();
b = input.nextInt();
try {
if(b==0)
throw new ArithmeticException("Divisor cannot be zero");//如果是异常,会扔出异常信息,即此处遇到异常,就会执行catch部分,catch部分执行完毕后,
//异常下面的语句正常执行
System.out.println(a/b);
}
catch (ArithmeticException ex) {//可以有多个catch针对不同异常,
//常见的有IOException是Io异常无效的输入,读文件时超出文件尾等,还有,RuntimeException越界异常,
//其包括ArithmeticException数学异常,一个整数除以0,注意浮点数的算术运算不抛出异常
//NullPointerException企图通过一个NULL引用变量访问一个对象,IndexOutBoundsException数组下标超出范围,
//IllegalArgumentExection无效参数
System.out.println("Exception: an integer cannot be divided by zero");
}
System.out.println("Execution continues......");
}
}
也可以对文件读取,改写等抓取异常
package a13;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileNotFoundExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a file name :");
String filename = input.nextLine();
try {
Scanner input1 = new Scanner(new File(filename));
System.out.println("file "+filename+" exit ");
}
catch (FileNotFoundException ex) {
System.out.println("Exception "+filename +" not found");
}
}
}