284、Java中级01 - 异常处理【什么是异常】 2019.11.25

1、异常

异常定义:
导致程序的正常流程被中断的事件,叫做异常

2、文件不存在异常

比如要打开d盘的LOL.exe文件,这个文件是有可能不存在的
Java中通过 new FileInputStream(f) 试图打开某文件,就有可能抛出文件不存在异常FileNotFoundException
如果不处理该异常,就会有编译错误
处理办法参见 异常处理

package exception;
  
import java.io.File;
import java.io.FileInputStream;
  
public class TestException {
  
    public static void main(String[] args) {
          
        File f= new File("d:/LOL.exe");
          
        //试图打开文件LOL.exe,会抛出FileNotFoundException,如果不处理该异常,就会有编译错误
        new FileInputStream(f);
          
    }
}

3、练习:异常

罗列出学习到目前为止,都接触过了哪些异常,分别在什么情况下会出现

NullPointerException 空指针异常
ArithmeticException 除数为零
ClassCastException 类型转换异常
OutOfIndexException 数组下标越界异常
ParseException 解析异常,日期字符串转换为日期对象的时候,有可能抛出的异常
OutOfMemoryError 内存不足

package exception;
 
public class exception_text {
 
    public static void main(String[] args) {
//      NullPointerException 空指针异常
        String s = null;
        System.out.println(s.length());
 
//      ArithmeticException 除数为零    
        int i = 1,j = 0,m;
        System.out.println(m=i/j);
         
//      ClassCastException 类型转换异常
        System.out.println("运行时异常,大多数发生在强制转换以及SQL映射异常时等才有");
         
//      OutOfIndexException 数组下标越界异常
        char[] cs = new char[10];
        cs[11] = 'o';
         
//      ParseException 解析异常,日期字符串转换为日期对象的时候,有可能抛出的异常
         
//      OutOfMemoryError 内存不足
         
    }
     
}

4、参考链接

[01] How2j - 异常处理系列教材 (一)- JAVA 异常 EXCEPTION

发布了309 篇原创文章 · 获赞 229 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/youyouwuxin1234/article/details/103244465