idea的使用/异常处理

1 IDEA使用

第1组:通用型

复制代码-copy ctrl + c
粘贴-paste ctrl + v
剪切-cut ctrl + x
撤销-undo ctrl + z
反撤销-redo ctrl + shift + z
保存-save all ctrl + s
全选-select all ctrl + a

第2组:提高编写速度

智能提示-edit alt + enter
提示代码模板-insert live template ctrl+j
使用xx块环绕-surround with … ctrl+alt+t
调出生成getter/setter/构造器等结构-generate … alt+insert
自动生成返回值变量-introduce variable … ctrl+alt+v
复制指定行的代码-duplicate line or selection ctrl+d
删除指定行的代码-delete line ctrl+y
切换到下一行代码空位-start new line shift + enter
切换到上一行代码空位-start new line before current ctrl +alt+ enter
向上移动代码-move statement up ctrl+shift+↑
向下移动代码-move statement down ctrl+shift+↓
向上移动一行-move line up alt+shift+↑
向下移动一行-move line down alt+shift+↓
方法的形参列表提醒-parameter info ctrl+p
批量修改指定的变量名、方法名、类名等-rename shift+f6
抽取代码重构方法-extract method … ctrl+alt+m
重写父类的方法-override methods … ctrl+o
实现接口的方法-implements methods … ctrl+i
选中的结构的大小写的切换-toggle case ctrl+shift+u
批量导包-optimize imports ctrl+alt+o

第3组:类结构、查找和查看源码

如何查看源码-go to class… ctrl + 选中指定的结构 或 ctrl+n
显示当前类结构,支持搜索指定的方法、属性等-file structure ctrl+f12
退回到前一个编辑的页面-back ctrl+alt+←
进入到下一个编辑的页面-forward ctrl+alt+→
打开的类文件之间切换-select previous/next tab alt+←/→
光标选中指定的类,查看继承树结构-Type Hierarchy ctrl+h
查看方法文档-quick documentation ctrl+q
类的UML关系图-show uml popup ctrl+alt+u
定位某行-go to line/column ctrl+g
回溯变量或方法的来源-go to implementation(s) ctrl+alt+b
折叠方法实现-collapse all ctrl+shift+ -
展开方法实现-expand all ctrl+shift+ +

第4组:查找、替换与关闭

查找指定的结构 ctrl+f
查找与替换-replace ctrl+r
直接定位到当前行的首位-move caret to line start home
直接定位到当前行的末位 -move caret to line end end
全项目搜索文本-find in path … ctrl+shift+f

第5组:调整格式

格式化代码-reformat code ctrl+alt+l
使用单行注释-comment with line comment ctrl + /
使用/取消多行注释-comment with block comment ctrl + shift + /
选中数行,整体往后移动-tab tab
选中数行,整体往前移动-prev tab shift + tab

2 异常类型

  1. 什么是异常?
    指的是程序在执行过程中,出现的非正常情况,如果不处理最终会导致JVM的非正常停止。

  2. 异常的抛出机制
    Java中把不同的异常用不同的类表示,一旦发生某种异常,就创建该异常类型的对象,并且抛出(throw)
    然后程序员可以捕获(catch)到这个异常对象,并处理;如果没有捕获(catch)这个异常对象,那么这个异常
    对象将会导致程序终止。

  3. 如何对待异常
    对于程序出现的异常,一般有两种解决方法:一是遇到错误就终止程序的运行。另一种方法是程序员在编写程序时,
    充分考虑到各种可能发生的异常和错误,极力预防和避免。实在无法避免的,要编写相应的代码进行异常的检测、
    以及异常的处理,保证代码的健壮性

  4. 异常的体系结构
    java.lang.Throwable:异常体系的根父类
    |–-java.lang.Error:错误。Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。
    一般不编写针对性的代码进行处理。去改代码
    |---- StackOverflowError、OutOfMemoryError

    public class ErrorTest {
        public static void main(String[] args) {
    
            //举例1:栈内存溢出的错误StackOverflowError
    //        main(args);
    
            //举例2:OutOfMemoryError: Java heap space
    //        byte[] arr = new byte[1024 * 1024 * 100]; //100mb
    
        }
    }
    

    |—java.lang.Exception:异常。我们可以编写针对性的代码进行处理。
    |----编译时异常:(受检异常)在执行javac.exe命令时,出现的异常。写代码时候就报错了
    |----- ClassNotFoundException

      public void test7(){
        Class clz = Class.forName("java.lang.String");
        }
    

    ​ |----- FileNotFoundException
    ​ |----- IOException

    public void test8() {
            File file = new File("D:\\hello.txt");
    
            FileInputStream fis = new FileInputStream(file); //可能报FileNotFoundException
        //可能找不到
    
    	   int data = fis.read(); //可能报IOException
        //可能拥堵
    		    while(data != -1){
                System.out.print((char)data);
                data = fis.read(); //可能报IOException
                    //可能没有关闭
            }
    
            fis.close(); //可能报IOException
        //可能
    
        }
    
    此时要在类前 throws FileNotFoundException,IOException处理可能`出现的情况.
    

    ​ |----运行时异常:(非受检异常)在执行java.exe命令时,出现的异常。
    ​ |---- ArrayIndexOutOfBoundsException

    //数字脚标越界
    public void test1(){
        int[] arr = new int[10];
        System.out.println(arr[10]);
    }
    
    
    

    ​ |---- NullPointerException

    //空指针异常-对象指向没有实体
        public void test2(){
            //1
            String str = "hello";
            str = null;
            System.out.println(str.toString());
    		//2
            int[] arr = new int[10];
            arr = null;
            System.out.println(arr[0]);
    		//3
            int[][] arr1 = new int[10][];
            System.out.println(arr1[0][0]);
        }
    

    ​ |---- ClassCastException

    public void test3(){
        Object obj = new String();
      String str = (String) obj;
    
        Date date = (Date) obj;  //强转错误
    }
    

    ​ |---- NumberFormatException

    public void test4(){
        String str = "123";
        str = "abc";
        int i = Integer.parseInt(str); //拆包类型不对
        System.out.println(i);
    }
    

    ​ |---- InputMismatchException

    //用户输入错误
    public void test5(){
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt(); //输入abc
        System.out.println(num);
    }
    

    ​ |---- ArithmeticException

public void test6(){
    int num = 10;
    System.out.println(num / 0); //计算错误
}

程序永久了之后

OOM: 可能产生内存泄露 , 堆的溢出

3 异常处理

方式一 try-catch-finally

(抓抛模型)

过程1:“抛”
​ 程序在执行的过程当中,一旦出现异常,就会在出现异常的代码处,生成对应异常类的对象,并将此对象抛出。
​ 一旦抛出,此程序就不执行其后的代码了。

过程2:“抓”
​ 针对于过程1中抛出的异常对象,进行捕获处理。此捕获处理的过程,就称为抓。
​ 一旦将异常进行了处理,代码就可以继续执行。

  1. 基本结构:
    try{
    //可能产生异常的代码 , 很多行
    }
    catch( 异常类型1 e ){
    … //当产生异常类型1型异常时的处置措施
    }
    catch( 异常类型2 e ){
    … //当产生异常类型2型异常时的处置措施
    }
    finally{
    //这里面的代码都要执行
    }
  2. 使用细节:

可能出现异常的代码声明在try语句中。一旦代码出现异常,就会自动生成一个对应异常类的对象。并将此对象抛出。
针对于try中抛出的异常类的对象,使用之后的catch语句进行匹配。一旦匹配上,就进入catch语句块进行处理。
一旦处理接触,代码就可继续向下执行
如果声明了
多个catch结构
不同的异常类型在不存在子父类关系的情况下,谁声明在上面,谁声明在下面都可以。
如果多个异常类型满足子父类的关系,则必须将子类声明在父类结构的上面。否则,报错。

public void test1(){
 try{
     Scanner scanner = new Scanner(System.in);
     int num = scanner.nextInt();
     System.out.println(num);

 }catch(NullPointerException e){ //子类
     System.out.println("出现了NullPointerException的异常");
 }catch(InputMismatchException e){  //子类
     System.out.println("出现了InputMismatchException的异常");
 }catch(RuntimeException e){ //父类
     System.out.println("出现了RuntimeException的异常");
 }

 System.out.println("异常处理结束,代码继续执行...");
}
}

catch中异常处理的方式:

  • 自己编写输出的语句。
  • printStackTrace():打印异常的详细信息。 (推荐)
  • getMessage():获取发生异常的原因。
  • try中声明的变量,出了try结构之后,就不可以进行调用了。
  • try-catch结构是可以嵌套使用的。
public void test2(){
     try{
         String str = "123";
         str = "abc";
         int i = Integer.parseInt(str);
         System.out.println(i);
     }catch(NumberFormatException e){
         e.printStackTrace();//不做处理 , 是为了之后能改代码 ,且用户遇到异常不是代码而是界面 .
         //或
//            System.out.println(e.getMessage());
     }

     System.out.println("程序结束");
//        System.out.println(str);

 }
  1. 开发体会:

**对于运行时异常:**↑↑↑↑↑↑↑↑↑↑↑↑
开发中,通常就不进行显示的处理了
一旦在程序执行中,出现了运行时异常,那么就根据异常的提示信息修改代码即可

**对于编译时异常:**↓↓↓↓↓↓↓↓↓↓↓↓↓
一定要进行处理。否则编译不通过。

public void test3() {
    try{

        File file = new File("D:\\hello.txt");

        FileInputStream fis = new FileInputStream(file); //可能报FileNotFoundException

        int data = fis.read(); //可能报IOException
        while(data != -1){
            System.out.print((char)data);
            data = fis.read(); //可能报IOException
        }

        fis.close(); //可能报IOException
    }catch(FileNotFoundException e){  //子类
        e.printStackTrace();
    }catch(IOException e){//父类
        e.printStackTrace();
    }

    System.out.println("读取数据结束....");
}
  1. finally的使用说明:
    4.1 finally的理解

我们将一定要被执行的代码声明在finally结构中。
更深刻的理解:无论try中或catch中是否存在仍未被处理的异常,无论try中或catch中是否存在return语句等,finally
中声明的语句都一定要被执行。

//此时catch中报错程序结束 不输出“程序结束”
public void test1(){
    try{
        String str = "123";
        str = "abc";
        int i = Integer.parseInt(str);
        System.out.println(i);
    }catch(NumberFormatException e){
        e.printStackTrace();

        System.out.println(10 / 0); //在catch存在异常
    }

    System.out.println("程序结束");
}
//就算catch报错, finally都会继续执行
public void test2(){
    try{
        String str = "123";
        str = "abc";
        int i = Integer.parseInt(str);
        System.out.println(i);
    }catch(NumberFormatException e){
        e.printStackTrace();

        System.out.println(10 / 0); //在catch存在异常

    }finally{
        System.out.println("程序结束");
    }
}
//例2 返回了1/-1 都会输出finally中的 “text结束”
//且在返回前 先执行finally 此时直接return 0 了
public class FinallyTest1 {
    public static void main(String[] args) {
        int result = test("12");
        System.out.println(result);
    }

    public static int test(String str){
        try{
            Integer.parseInt(str);
            return 1;
        }catch(NumberFormatException e){
            return -1;
        }finally{
            System.out.println("test结束");
            return 0}
    }
}
//例子
//但是在finally中 临时的计算数据都是局部变量 finally中的运算在新的一个栈帧
//而return的是原来那个栈帧

public class FinallyTest4 {
    public static void main(String[] args) {
        int result = test(10);
        System.out.println(result);
    }

    public static int test(int num) {
        try {
            return num;
        } catch (NumberFormatException e) {
            return num--;
        } finally {
            System.out.println("test结束");
//            return ++num;
            ++num;
        }
    }
}
4.2 什么样的代码我们一定要声明在finally中呢?

我们在开发中,**有一些资源(比如:输入流、输出流,数据库连接、Socket连接等资源),在使用完以后,必须显式的进行关闭操作,否则,GC不会自动的回收这些资源。**进而导致内存的泄漏。
为了保证这些资源在使用完以后,不管是否出现了未被处理的异常的情况下,这些资源能被关闭。我们必须将这些操作声明
在finally中!

2 try-catch的嵌套使用

  //重点:将流资源的关闭操作声明在finally中
public void test4() {
    FileInputStream fis = null;
    try{
        File file = new File("D:\\hello.txt");

        fis = new FileInputStream(file); //可能报FileNotFoundException


        int data = fis.read(); //可能报IOException
        while(data != -1){
            System.out.print((char)data);
            data = fis.read(); //可能报IOException
        }


    }catch(FileNotFoundException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        //重点:将流资源的关闭操作声明在finally中
        try {
            if(fis != null)
                fis.close(); //可能报IOException
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
  1. 面试题
    final 、 finally 、finalize 的区别
方式二 throws+异常类型
  1. 格式:在方法的声明除,使用"throws 异常类型1,异常类型2,…"
  2. 举例:
public class ThrowsTest {
    public static void main(String[] args)  {
        method3();
        try{
            method2();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }

    }
    public static void method3(){
        try{
            method2();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }

    }
    public static void method2()throws FileNotFoundException, IOException{

        method1();

    }
    public static void method1() throws FileNotFoundException, IOException {
        File file = new File("D:\\hello.txt");

        FileInputStream fis = new FileInputStream(file); //可能报FileNotFoundException

        int data = fis.read(); //可能报IOException
        while (data != -1) {
            System.out.print((char) data);
            data = fis.read(); //可能报IOException
        }

        fis.close(); //可能报IOException
    }

}
  1. 是否真正处理了异常?

从编译是否能通过的角度看,看成是给出了异常万一要是出现时候的解决方案。此方案就是,继续向上抛出(throws)。
但是,此throws的方式,仅是将可能出现的异常抛给了此方法的调用者。此调用者仍然需要考虑如何处理相关异常。
从这个角度来看,throws的方式不算是真正意义上处理了异常。

  1. 方法的重写的要求:(针对于编译时异常来说的)
    子类重写的方法抛出的异常类型可以与父类被重写的方法抛出的异常类型相同

或是父类被重写的方法抛出的异常类型的子类

public class OverrideTest {
    public static void main(String[] args) {

        Father f = new Son();

        try{
            f.method1();   
        }catch(IOException e){
            e.printStackTrace();
        }

        Number n = f.method4();  //多态
    }
}


class Father{
    public void method1() throws IOException {
    }
    
    public void method2(){
    }
    
    public void method3(){
    }
    
    public Number method4(){
        return null;
    }
    
}

class Son extends Father{
    public void method1() throws FileNotFoundException { //是抛出异常的子类

    }
//    public void method2() throws FileNotFoundException{
//
//    }
    public void method3() throws RuntimeException{
    }
    
    public Integer method4(){
        return null;
    }
}
  1. 开发中,如何选择异常处理的两种方式?(重要、经验之谈)
  • 如果程序代码中,涉及到资源的调用(流、数据库连接、网络连接等),则必须考虑使用try-catch-finally来处理,
    保证不出现内存泄漏。(要手动把他关闭)
  • 如果父类被重写的方法没有throws异常类型,则子类重写的方法中如果出现异常,只能考虑使用try-catch-finally
    进行处理,不能throws。 (因为throws在重写中只能是父类方法throws中的子类,但父类中没有 所以只能用try)
  • 开发中,方法a中依次调用了方法b,c,d等方法,方法b,c,d之间是递进关系。此时,如果方法b,c,d中有异常,
    我们通常选择使用throws,而方法a中通常选择使用try-catch-finally。

4 手动抛出异常

  1. 为什么需要手动抛出异常对象?

在实际开发中,如果出现不满足具体场景的代码问题,我们就有必要手动抛出一个指定类型的异常对象。

比如要求输入数字却得到英文,就要让输入英文的情况弹出让用户修改

  1. 如何理解"自动 vs 手动"抛出异常对象?

过程1:“抛”
“自动抛” : 程序在执行的过程当中,一旦出现异常,就会在出现异常的代码处,自动生成对应异常类的对象,并将此对象抛出。

​ “手动抛” :程序在执行的过程当中,不满足指定条件的情况下,我们主动的使用"throw + 异常类的对象"方式抛出异常对象。

过程2:“抓”
狭义上讲:try-catch的方式捕获异常,并处理。
广义上讲:把“抓”理解为“处理”。则此时对应着异常处理的两种方式:① try-catch-finally ② throws

  1. 如何实现手动抛出异常?
    在方法内部,满足指定条件的情况下,使用"throw 异常类的对象"的方式抛出。
  2. 注意点:throw后的代码不能被执行,编译不通过。
  3. 面试题:throw 和 throws 的区别? “上游排污,下游治污”
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值