异常 异常类Exception
异常:程序中一些处理不了的特殊情况,当程序中出现异常,就会中断程序,代码不会继续运行
异常的分类
检查型异常(编译异常):在编译时就会抛出的异常(代码上会报错),需要在代码中编写处理方式 (和程序之外的资源进行访问) 直接继承Exception
运行时异常:在代码的运行阶段,可能会出现的异常,可以不用明文处理。可以通过代码避免异常的发生 继承RunTimeException
处理异常 try……catch……finally
处理文件,访问系统之外的异常
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class EasyException {
public static void main(String[] args) throws IOException {
//文件类型File
File file= new File("D:\\easy.txt");
//检查性异常(编译异常)
FileInputStream fis=null;
try{
//尝试捕捉异常 其中是可能会抛出异常的代码
fis = new FileInputStream(file);
}catch (FileNotFoundException e) {//形参 变量
//捕捉到异常后要处理的代码块
e.printStackTrace();//打印异常日志
}finally{
//无论是否出现异常都会执行的代码块
//一般用来关闭资源
if(fis!=null){
try{
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
try处理多种异常
public class EasyException {
public static void main(String[] args) throws IOException {
try{
System.out.println(12/0);
Object strA="";
System.out.println((Integer)strA);
fis = new FileInputStream(file);
}catch(ArithmeticException e){
//出现ArithmeticException要执行的代码
System.out.println("出现ArithmeticException");
}catch(ClassCastException e){
System.out.println("出现ClassCastException");
}catch(FileNotFoundException e){
System.out.println("出现FileNotFoundException");
}finally{
if(fis!=null){
try{
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
catch合并处理方案,一个catch块捕捉多种异常,使用 | 声明多种异常
public class EasyException {
public static void main(String[] args) throws IOException {
try{
System.out.println(12/0);
Object strA="";
System.out.println((Integer)strA);
fis = new FileInputStream(file);
}catch(ArithmeticException|ClassCastException|FileNotFoundException e){
}
}
}
catch异常捕捉的顺序:子类异常优先处理,父类异常后置处理
public class EasyException {
public static void main(String[] args) throws IOException {
try{
List list = new ArrayList();
list.remove(8);//Indexout
int[] arr = new int[2];
arr[8]=22;//ArrayIndex
String strA="abc";
strA.charAt(8);//StringIndex
} catch(ArrayIndexOutOfBoundsException e){//子类异常优先处理
e.printStackTrace();
} catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
catch块声明父类异常,捕捉所有子类异常
public class EasyException {
public static void main(String[] args) throws IOException {
try{
System.out.println(12/0);
Object strA="";
System.out.println((Integer)strA);
fis = new FileInputStream(file);
}catch(Exception e){
}
}
}
catch块抛出异常,如果没有finlly就会中断程序
如果有finally,就会运行finally 并且正常返回,此方法正常运行
public static int test(){
try{
System.out.println(12/0);
return 1;
}catch(Exception e){
System.out.println(12/0);
return 2;
}finally{
return 3;
}
}
public static void main(String[] args) {
System.out.println(test());//3
}
try不能单独编写,必须有其他语句块,try块中没有检查型异常不能在try块中随意捕捉
public static void testB(){
FileInputStream fis=null;
try{
System.out.println(12/0);
}catch(Exception e){
e.printStackTrace();
}
try{
System.out.println(12/0);
//不能出现检查属性异常
//fis = new FileInputStream(file);
}finally{
}
}
自定义异常throw,throws
throw
作用: throw
关键字用于在方法体内实际抛出一个异常实例。当程序运行到throw
语句时,指定的异常会被创建并抛出,立即终止当前方法的执行,并将控制权转移给包含该方法的调用者的异常处理机制。
使用时机: 当检测到某种错误条件或异常情况时,在方法内部使用throw
来抛出一个异常对象,这个对象可以是系统预定义的异常类的实例,也可以是自定义异常类的实例。
特点: throw
总是伴随着一个异常实例,且其后的代码不会被执行,因为一旦抛出异常,当前的代码路径就会被中断。
throws
作用: throws
关键字用于声明方法可能抛出的异常类型,它出现在方法签名之后。这告知调用者该方法执行时可能会遇到的异常情况,要求调用者要么处理这些异常(使用try-catch
语句块),要么继续向上层方法抛出这些异常。
使用时机: 当一个方法无法处理或不打算处理某些异常时,可以在方法声明中使用throws
来声明这些异常。这样做可以强制调用者意识到潜在的异常风险并做出相应的处理准备。
特点: throws
后面可以跟随一个或多个异常类名,用逗号分隔,表示该方法可能抛出多种类型的异常。并且,throws
声明并不意味着异常一定会被抛出,它只是声明了一种可能性。
import java.io.IOException;
public class EasyExceptionA {
}
class BigStudent extends Exception {
public void info() throws StudentNameIsNullException{
}
}
//自定义异常
class Student{
String name;
//throws 声明方法中可能抛出的异常
//throws 声明抛出多种异常
//方法重写:子类对父类继承过来的方法进行重新定义
//约束:返回值类型 方法名 参数列表不能变
//访问权限只能更开放
//抛出的异常只能更精确(范围更小),不能扩大
public void info() throws StudentNameIsNullException,NullPointerException,IOException{
//name==null是一钟特殊情况,不符合业务需求
if(name==null){
throw new StudentNameIsNullException("student name is null");
}
System.out.println("我的名字是"+name);
}
//运行时异常可以不用throws
public void infoA() throws Exception{
if(name==null){
//throw new NullPointerException("student name is null");
//throw new RuntimeException("student name is null");
throw new Exception();
}
}
}
//检查型异常是Exception的直接子类
class StudentNameIsNullException extends Exception{
public StudentNameIsNullException(String message) {
super(message);
}
}
文件File
//在java中声明一个文件 传入字符串当作文件地址
File f=new File("D:\\easy.txt");
常用方法
是否存在该文件 .exists
boolean bool;
bool=f.exists();
System.out.println(bool);//存在返回true,不存在返回false
创建文件 .createNewFile();删除文件 .delete()
import java.io.File;
import java.io.IOException;
public class EasyFile {
public static void main(String[] args) {
//创建文件
if(!bool){
try {
bool = f.createNewFile();
if(bool){
System.out.println("成功创建文件");
}
}catch (IOException e){
e.printStackTrace();
}
}else {
//删除文件夹时,文件夹必须是空的文件夹
f= new File("D:\\123");
bool=f.delete();
System.out.println("成功删除文件"+bool);
}
}
}
获取是否是文件 .isFile()
bool = f.isFile();
System.out.println(bool);
是否是文件夹 .isDirectory()
bool = f.isDirectory();
System.out.println(bool);
创建文件夹 .mkdir()
f.mkdir();//前面的路径必须都存在
查看文件大小 .length()
f=new File("文件路径");
long len=f.length();
IO(输入流/输出流)
此处的“流”为流动的数据,是二进制的
分类:
根据流动的方向不同分为输入流和输出流
根据流动的介质(单位)不同分为字符流和字节流,字符流只能读取文本txt .xml .properties .html .yml ;字节流可以读取所有的文件类型
根据功能(作用)不同分为 节点流和工具流
import java.io.*;
public class EasyFileIO {
public static void main(String[] args) {
//字节输入流
InputStream is;
//字节输出流
OutputStream os;
//字符输入流
Reader r;
//字符输出流
Writer w;
}
方法1
返回读取的字节数:read(byte[] b)
方法返回实际读取的字节数,这可以少于请求的字节数(即b.length
)。当到达文件的末尾时,它会返回-1
。
public static void readFile() {
FileInputStream fis = null;
try{
fis=new FileInputStream("d:\\easy.txt");
byte[] arr= new byte[1024];
//读取多少就转换多少
int length=0;
while((length=fis.read(arr))!=-1){
//arr中就是读取到的数据
String str=new String(arr,0,length);
//String.valueOf(arr);
System.out.print(str);
}
}catch(IOException e){
e.printStackTrace();
}finally {
if(fis!=null){
try{
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
方法2
转换流:
转换流主要指的是在计算机编程中,特别是在java的IO流处理中,用于在字节流和字符流之间进行转换的一种技术。 这种转换通常通过使用InputStreamReader和
OutputStreamWriter类来实现,它们分别负责将字节流转换为字符流和将字符流转换为字节流。
缓冲流:
缓冲流,也叫高效流,它可以对那些基本的字节字符流进行增强,达到提高数据的读写能力。创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。
字节缓冲流:BufferedInputStream
,BufferedOutputStream
字符缓冲流:BufferedReader
,BufferedWriter
public static void readFileBuffer(){
//文件字节输入流
FileInputStream fis=null;//节点流
//工具流:
// 转换流
InputStreamReader isr=null;
// 缓冲流
BufferedReader br=null;
try{
fis=new FileInputStream("D:\\easy.txt");
isr=new InputStreamReader(fis);
br=new BufferedReader(isr);//8192
String line = br.readLine();
System.out.println(line);
}catch(IOException e){
e.printStackTrace();
}finally {
if(fis!=null){
try{
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
方法3
fos = new FileOutputStream(name,append);这里的append默认为false(不写时),为false时写入文件会覆盖文件内容;为true时会追加文件内容。
public static void writeFile(){
String str="烟笼寒水月笼沙";
byte[] arr=str.getBytes();
FileOutputStream fos=null;
try{
fos = new FileOutputStream("D:\\easy.txt",true);
fos.write(arr);
}catch(IOException e){
e.printStackTrace();
}finally{
if(fos!=null){
try{
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
方法4
只有实现了Serializable或Externalizable接口的类的对象才能被序列化,否则抛出异常
import java.io.*;
public class EasyFileIO {
public static void main(String[] args) {
}
public static void writeObject(){
//将内存对象转换成序列(流),叫序列化
//这个对象必须是可序列化的
Staff staff=new Staff();
staff.name="张三";
staff.sex="男";
staff.salary=3500;
ObjectOutputStream oos=null;
FileOutputStream fos=null;
try{
fos = new FileOutputStream("D:\\easy.txt");
oos = new ObjectOutputStream(fos);
oos.writeObject(staff);
}catch(IOException e){
e.printStackTrace();
}finally{
if(oos!=null){
try{
oos.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(fos!=null){
try{
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
public class Staff implements Serializable {
String name;
int salary;
String sex;
@Override
public String toString() {
return "Staff{" +
"name='" + name + '\'' +
", salary=" + salary +
", sex='" + sex + '\'' +
'}';
}
}
方法5
创建对象的方式1.new;2.clone;3.反序列;4.反射
public static void readObject() {
//将对象序列读入程序,转换成对象的方式:反序列化
FileInputStream fis =null;
ObjectInputStream ois =null;
try{
fis = new FileInputStream("D:\\easy.txt");
ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
System.out.println(obj);
//反序列化会创建新的对象
}catch(Exception e){
e.printStackTrace();
}finally{
if(ois!=null){
try{
ois.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(fis !=null){
try{
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}