You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Java/Java面向对象 - Java中的异常.txt

97 lines
2.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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 **********/
}
}