|
|
1.Java 中的异常处理机制
|
|
|
编译出错,提示“公有类HelloWorld必须在HelloWorld.java文件中定义”
|
|
|
(IOException及其子类(FileNotFoundException等),都属于检测型异常;运行时异常可以处理,也可以不处理,是可选的;
|
|
|
所有的异常类是从 java.lang.Exception 类继承的子类)
|
|
|
运行时报错,提示除数不能为0
|
|
|
2.捕获异常
|
|
|
package step2;
|
|
|
import java.util.Scanner;
|
|
|
public class Task {
|
|
|
public static void main(String[] args) {
|
|
|
Scanner sc = new Scanner(System.in);
|
|
|
int num1 = sc.nextInt();
|
|
|
int num2 = sc.nextInt();
|
|
|
/********* Begin *********/
|
|
|
try{
|
|
|
System.out.println(num1/num2);}
|
|
|
catch(ArithmeticException e){
|
|
|
System.out.print("除数不能为0");
|
|
|
}
|
|
|
/********* End *********/
|
|
|
}
|
|
|
}
|
|
|
3.抛出异常
|
|
|
package step3;
|
|
|
import java.io.File;
|
|
|
import java.io.FileInputStream;
|
|
|
import java.io.FileNotFoundException;
|
|
|
import java.io.IOException;
|
|
|
public class Task {
|
|
|
public static void main(String[] args)throws FileNotFoundException{
|
|
|
test();
|
|
|
}
|
|
|
public static void test()throws FileNotFoundException{
|
|
|
File file = new File("abc");
|
|
|
if(!file.exists()){ //判断文件是否存在
|
|
|
//文件不存在,则 抛出 文件不存在异常
|
|
|
throw new FileNotFoundException("该文件不存在");
|
|
|
}else{
|
|
|
FileInputStream fs = new FileInputStream(file);
|
|
|
}
|
|
|
}
|
|
|
/********* End *********/
|
|
|
}
|
|
|
4.自定义异常
|
|
|
package step4;
|
|
|
import java.util.Scanner;
|
|
|
public class Task {
|
|
|
/********* Begin *********/
|
|
|
public static void main(String[] args)throws MyException {
|
|
|
Scanner sc = new Scanner(System.in);
|
|
|
String username = sc.next();
|
|
|
//判断用户名
|
|
|
if(username.length()<3){
|
|
|
throw new MyException("用户名小于三位Exception");
|
|
|
}
|
|
|
else{
|
|
|
System.out.println("用户名格式正确");
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
class MyException extends Exception{
|
|
|
public MyException(){}
|
|
|
public MyException(String msg){
|
|
|
super(msg);
|
|
|
}
|
|
|
}
|
|
|
/********* End *********/
|
|
|
5.Java异常处理之try-catch之异常捕获
|
|
|
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
public class ExcTest {
|
|
|
public static void main(String[] args) {
|
|
|
// 请在Begin-End间编写代码
|
|
|
/********** Begin **********/
|
|
|
// 第一步:接收给定的整数
|
|
|
Scanner input=new Scanner(System.in);
|
|
|
int a = input.nextInt();
|
|
|
int b = input.nextInt();
|
|
|
int x;
|
|
|
// 第二步:求给定两个数的商,并捕获除数为0的异常
|
|
|
try{
|
|
|
x = a / b;
|
|
|
}
|
|
|
catch(Exception e){
|
|
|
{
|
|
|
System.out.println("除数不能为0");
|
|
|
}
|
|
|
}
|
|
|
if(b != 0){
|
|
|
System.out.println(a / b);
|
|
|
}
|
|
|
/********** End **********/
|
|
|
|
|
|
}
|
|
|
}
|