Java中的异常分为两类
:需查和不需查异常。简单来讲需查异常是业务逻辑异常,需要程序员检查处理;不需查异常系统错误,程序员不能处理。Java中用try catch finally语法来处理.
需查异常
一般继承RuntimeException.java
package com.eve.project.exception;
public class TestException extends RuntimeException{
public TestException(String message){
super(message);
}
}
这样一个异常报错就写好了 存放在com.eve.project.exception.TestException.java里面
那接下来就是当你需要抛出异常的时候调用这个异常
我们创建一个com.eve.project.test.IoTest.java
package com.eve.project.test;
import com.eve.project.exception.*;
public class Iotest {
public static void ioMain(){
throw new TestException("这个字符串会被抛出作为异常提示信息");
}
public static void main(String[] args){
ioMain();
}
}
运行一下这个Iotest文件 就会看到异常被抛出啦
不需查异常
这里是一个文件读取的代码 里面有几处catch 这种异常现在非常好写,只要你写下代码。编辑器会给你自动提示 你只需要点一下就会自动生成异常处理。
package com.eve.exam.dao;
import com.eve.exam.exception.ExamException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ExamAnswerOperator {
public List<String> readExam(File file) {
FileReader fr = null;
BufferedReader br = null;
List<String> content = new ArrayList<String>();
try {
if (file==null || file.length()<=0){
throw new ExamException("文件名称不为空");
}
//打开文件
fr = new FileReader(file);
br = new BufferedReader(fr);
//读文件,并且把数据存在list合集
String line;
while ((line = br.readLine())!=null){
//trim去除字符串首尾空格
if (!line.trim().equals("")){
content.add(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭文件,要求:反方向倒着关闭资源,先关闭br,再关闭fr
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
}
顺便把调用这个文本读取class的地方代码附上
String fileName = this.getClass().getClassLoader().getResource("文件名.txt").getPath();
File file = new File(fileName);
List<String> list = examAnswerOperator.readExam(file);
但你的文件存在resource下 就可以这样读取文件 再丢到你写好的文件处理类里
import javax.swing.*;
import java.util.Scanner;
public class CMUtil {
public static char getUserAction(){
char[] validKey ={'1','2','3','4'};
char key=0;
Scanner scanner = new Scanner((System.in));
while (scanner.hasNext()){
//接收键盘输入
String str = scanner.next();
if (str.length() != 1){
JOptionPane.showMessageDialog(null,"无法识别,重新输入","操作提示",JOptionPane.PLAIN_MESSAGE);
continue;
}
str = str.toUpperCase();
//大写
key = str.charAt(0);
for (char k:validKey){
if(k == key){
return key;
}
}}
return key;
}
public static String readString(int limit){
String operation = null;
Scanner scanner = new Scanner((System.in));
while (scanner.hasNext()){
//接收键盘输入
operation = scanner.next();
if (operation.length()>limit){
System.out.println("请按提示输入");
}
else{
return operation;
}
}
return operation;
}
public static int readInt(){
int cardId = 0;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String id = scanner.next();
cardId = Integer.parseInt(id);
return cardId;
}
}
}
第一个是有规定输入的类型,第二个是读取string 如果这里不return掉,因为while的关系就可以一直输入一直输入,然后第三个是读取int