try-catch和多catch代码块

1、try-catch语句

基本try-catch语句语法如下:

try{

//可能会发生异常的语句

}catch{

//处理异常e

}

代码示例

第一种方式:将异常抛给上一级领导处理,这种做法是不负责的方法    throws ParseException

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TryCatch {
	public static void main(String[] args) {
		Date date = readDate();
		System.out.println("日期 = " + date);
	}

	private static Date readDate() throws ParseException{
//		try {
			String str = "2020-03-08";
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			//从字符串中解析日期
			Date date = df.parse(str);
			return date;
//		} catch (ParseException e) {
//			System.out.println("处理ParseException...");
//			e.printStackTrace();
//		}
//		return null;
	}
}

第二种方式:try-catch 自己处理

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TryCatch {
	public static void main(String[] args) {
		Date date = readDate();
		System.out.println("日期 = " + date);
	}

	private static Date readDate() {
		try {
			String str = "2020-03-08";
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			//从字符串中解析日期
			Date date = df.parse(str);
			return date;
		} catch (ParseException e) {
			System.out.println("处理ParseException...");
			e.printStackTrace();
		}
		return null;
	}
}

2、多catch语句

多catch代码块语法如下:

try{

//可能会发生异常的语句

}catch(Throwable e){

//处理异常e

}catch(Throwable e){

//处理异常e

}catch(Throwable e){

//处理异常e

}

代码示例

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TryCatchCatch {

	public static void main(String[] args) {
		Date date = readDate();
		System.out.println("日期 = " + date);
	}

	private static Date readDate() {
		//IO文件输入流
		FileInputStream readfile = null;
		//IO文件输出流
		InputStreamReader ir = null;
		BufferedReader in= null;
		try {
			//通过FileInputStream读取一个文件文件
			readfile = new FileInputStream("readme.txt");
			ir = new InputStreamReader(readfile);
			in = new BufferedReader(ir);
			//读取文件中的一行数据
			String str = in.readLine();
			if(str == null){
				return null;
			}
			//初始化时间格式
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			//格式化时间格式
			Date date = df.parse(str);
			return date;
		} catch (FileNotFoundException e) {
			System.out.println("处理FileNotFoundException...");
			e.printStackTrace();
		} catch (IOException e){
			System.out.println("处理IOException...");
			e.printStackTrace();
		}catch (ParseException e){
			System.out.println("处理ParseException...");
			e.printStackTrace();
		}
		return null;
	}

}
发布了96 篇原创文章 · 获赞 13 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_39559301/article/details/104743598
今日推荐