1    常用

1.1    添加null处理方法(查询sql针对String类型字段)

/**
     * 空值处理
     * @param sStr
     * @return
     */
    private static String NulltoString(String sStr){
        if(sStr==null)    return "";
        else return sStr;
    }

 

1.2    主动抛出异常

抛出Exception大异常时,方法上要加抛异常

抛出RunTimeException异常时,方法上不需要跑异常

public class ExceptionTest {
    public void exceptionTest1() throws Exception {
        throw new Exception();
    }

    public void exceptionTest2(){
        throw new RuntimeException();
    }
}

 

1.3    IO异常处理

记得关闭IO流

 @Test
    public void testIOException(File data) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = data.toURL().openStream();
        } catch (IOException e) {
            log.error("IOExceptionTest->testIOException->error1",e);
            throw e;
        } finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("IOExceptionTest->testIOException->error2",e);
                    throw e;
                }
            }
        }

 

1.4    异常类型校验(不管什么异常接的,抛出来的还是原异常)

@Test
    public void testExceptionTyp(){
        try {
            test2();
        } catch (NumberFormatException e1){
          log.error("NumberFormatException");
        } catch (Exception e) {
            log.error("Exception");
        }

    }


    public void test2(){
        try {
            test1();
        } catch (Exception e) {
            throw e;
        }
    }


    public void test1(){
        throw new NumberFormatException("1");
    }
12:49:22.494 [main] ERROR ExceptionTypTest - NumberFormatException

Process finished with exit code 0

 

 

N    规范

N.1    异常的分类

分为Exception和Error

Exception和Error都继承自Throwable,在Java中只有Throwable类型的实例才可以被抛出或捕获。Error指正常情况下不太可能出现的情况,绝大部分的Error或导致程序崩溃,
处于非正常的不可恢复的状态,如OutOfMemoryError、StackOverflowError。是程序中不应该试图捕获的严重问题。Exception是程序正常运行中可以预料的意外情况,可以捕获并处理。

 

N.2    运行时异常和一般异常的区别

受检查异常:在编译时被强制检查的异常。在方法的声明中声明的异常。(举例:ClassNotFoundException、IOException)不受检查异常:不受检查异常通常是在编码中可以避免的逻辑错误,
根据需求来判断如何处理,不需要再编译期强制要求。

 

N.3    几种常见的运行时异常

运行时异常RuntimeException是所有不受检查异常的基类。NullPointerException、ClassCastException、NumberFormatException、IndexOutOfBoundsException。

 

posted on 2021-07-24 20:24  菜鸟乙  阅读(65)  评论(0)    收藏  举报