Java 新人培训 — 异常处理

异常

异常不是编译时的错误(Error),异常是运行时错误(Exception)

 

异常处理流程


代码出现错误后,它会先在原函数代码内部寻找是否有try catch语句,如果没有,则找到调用这个函数的函数内部寻找,如果还没有就会交给java虚拟机,虚拟机会直接结束掉程序,返回异常信息.
如果异常交由 JVM 处理,JVM 会结束掉程序,并将异常信息输出到日志中,在 Android 上体现为 App 闪退。为了提高用户体验,我们要尽可能的处理可能发生的异常.

异常处理


  • try catch
public BufferedReader readFile(String path) {
        /*打开path指定路径下的文件
        * 可能抛出的异常 FileNotFoundException 文件不存在
        */
        FileInputStream fis = null;
        try {
            //可能出现错误的代码块
            fis = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            //catch 可能出现的异常
            e.printStackTrace();//打印异常信息(函数调用栈)
        }
        BufferedReader brd = new BufferedReader(new InputStreamReader(fis));
        return brd;
    }

 

  • throws
    如果你不想自己处理可能发生的异常,throws 可以将异常抛给调用该方法的方法进行处理,如果是 main 方法,再抛出时就会交由虚拟机处理.
public BufferedReader readFile(String path) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream(path);
        BufferedReader brd = new BufferedReader(new InputStreamReader(fis));
        return brd;
    }

 

异常的分类



如果抛出的异常为RuntimeException的子类,那么可以不进行捕获处理,如果是Exception的其它子类那么必须进行捕获处理,如果未进行捕获处理,但只要没有调用此方法,依然可以正常运行.
根据多态,如果你不能确定抛出的的异常类型,则可以 catch 它们的父类型 Exception

        try {
            //可能出现错误的代码块
            fis = new FileInputStream(path);
        } catch (Exception e) {
            //catch 可能出现的异常
            e.printStackTrace();//打印异常信息(函数调用栈)
        }

 

自定义异常


我们可以根据不同的业务需求,选择不同的父类,如 RuntimeException,Exception …

class LessMoneyException extends RuntimeException {
    public LessMoneyException(String s) {
        super(s);
    }
}

class TooMuchMoneyException extends Exception {
    public TooMuchMoneyException(String s) {
        super(s);
    }
}

当我们在发现代码执行过程中出现错误时,我们可以选择不去处理这个错误,而是throw(抛出)一个异常,让调用该函数的上下文来处理这个错误,这么做的原因通常是你再将自己实现的函数封装起来,供给他人使用,那么最好的办法不是自己处理异常,而是将异常抛给使用者,让他根据具体情况来处理错误.

public int foo2(ArrayList<Integer> list){
    if(list == null){
        throw new NullPointerException("list is null");
    }else {
        return list.size();
    }
}

 

注意事项


  1. 对于一个代码块来说,内部的语句在执行过程中可能会抛出多种异常,我们可以捕获不同类型的异常,针对具体问题做出不同的处理
public int foo1() {
    String a = null;
    String b = "20";
    String c = "0";
    int result = -1;
    try {
        result = Integer.valueOf(a) * Integer.valueOf(b) / Integer.valueOf(c);
    } catch (NumberFormatException e) {
        System.out.println("字符串转换整数错误,请检查被被转换字符串");
    } catch (ArithmeticException e) {
        System.out.println("出现了算术异常,可能为除零错误");
    }
    return result;
}

 
2. 当程序出现异常后,无论异常是否被处理,出现异常的代码后的语句都不再被执行,所以要注意因为异常导致的初始化及重置问题
如果你在 IDE 中编写了如下代码,在 return 语句出会出现错误提醒,因为 try 代码块中为可能出现异常的语句,则其内的赋值语句不一定会被成功执行,并不能确保变量一定被初始化,同时如果 i 变量的赋值出现问题,j 的赋值语句完全不会被执行.
Variable 'i' might not have been initialized

    public double foo2() {
        double i;
        double j;
        try {
            i = Math.PI;
            j = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

 
3. 可以使用finally来对状态进行统一管理,如资源清除,变量重置,关闭打开的文件等

public void trans(int card1, int card2) {//从card1向card2转账1000
    int temp1 = card1, temp2 = card2;
    try {
        card1 -= 1000;
        if (card1 < 0) {
            throw new LessMoneyException("钱太少了");
        }
        card2 += 1000;
        if (card2 > 1001) {
            throw new TooMuchMoneyException("要那么多钱干嘛");
        }
    } catch (LessMoneyException e) {
        e.printStackTrace();
    } catch (TooMuchMoneyException e) {
        e.printStackTrace();
    } finally {
        card1 = temp1;
        card2 = temp2;
    }
}

Java 新人培训 — 异常处理》有72个想法

  1. KelErex说:

    Amoxicillin Buy Canada Cheap Propecia Generic Vipps Canadian Pharmacy Reviews [url=http://cialibuy.com]Cialis[/url] Streaming Levitra Cialis Y Colesterol Toddler Ear Infections Amoxicillin And Augmentin

  2. LesCack说:

    Cialis Principio Attivo Levitra Uk Cheap Doxycycline Online No Prescription [url=http://cialibuy.com]Cialis[/url] Viagra O Levitra Pharmacy Uk Silagra Cialis Levitra Direct From India

  3. theanof说:

    You have the choice of completing old assignments and missing the new ones or skipping the old ones to keep up with the rest of class and seeing your overall grades suffer as a result.
    custom paper In a nutshell, by subscribing to the services of an exceptional research paper service, you will be entitled to receive a ready to research paper that will answer the question at hand in a well-structured and thought out manner.

  4. abnoda说:

    Depending on your wagering preferences and habits, bonuses with wagering requirements may not offer any added value to your play and you may decide not to accept them.
    real casino Despite the fact that there have been a multitude of entrants eyeing the marketplace, it is expected that there will be a shakeout in the marketplace after actual operations commence, and several companies will establish a dominant position in the market.

  5. LonyVoxy说:

    Because the complaints about plagiarism are severe, they were eagerly searching for academic writing aid provider, which is trustworthy, and offers high-quality papers on time, and this is how they found us. paper help When working on every other word, phrase, sentence or the whole page, we focus on creative approach in order to ensure every product you receive, like lab reports or term papers, is up to the existing writing standards.

  6. WouffCed说:

    Elements of fiction essay examples how to write my hobbies essay, what is the average essay score on act, essay on man is born free but everywhere he is in chains. paper help Then again, a customer is allowed to monitor all the writing process of his or her paper by ordering the writer to provide a draft of the ongoing order so that clarifications can be passed over to the writer when need be.

  7. expism说:

    This furniture line is especially appealingin toned-down colours, as well asvarious patterns, including striped,checked or flowers. gmp course online The communication was very quick and easy, and we loved all the recommendations you gave us for the local restaurants within walking distance and places to visit.

  8. ovanty说:

    Ausgewahlte arbeiten zur zahlentheorie und zur geometrie mit d hilberts gedachtnisrede auf h minkowski. author courses Still the love is always there, even when we must take that long sleep, to run free in a distant land.

  9. pelvign说:

    Heute ist es so, dass wir hier sehr schnell merken, dass das was hier geschieht, mit nichts anderem zu vergleichen ist, was wir bisher gekannt bzw. thefereviewcourse Demadi ratus insulam istam non igootara fuisse, qai haoc ob causam observationes suas ante concionem cum populo comraunicaret.

  10. twesee说:

    Subscriptions automatically renew unless auto-renew is turned off at least 24-hours before the end of the current period. the fe review course Theorized by several strands of contemporary feminist theory, intersectionality proves to be a difficult concept to put in practice in empirical investigation.

  11. expism说:

    Ensure a consistent, profitable growth in sales revenues within your defined geographic area by implementing initiatives to grow sales. institutosomosiguais Nanoelectronics, spintronics and nanomagnetics, non-volatile electronics and low dissipation devices, quantum device and systems, frontier materials by molecular beam epitaxy, photonics and energy.

  12. Elimadab说:

    Lommefilm started of by working together with film and music festivals, but soon saw a much greater potential in using the method to teach and communicate to young people. carryingthefire.org Web sitemight be experiencing technical difficulties, or you may need to adjustyour browser settings.

  13. smore traiolit说:

    I must show appreciation to the writer for bailing me out of this predicament. After looking through the world wide web and obtaining principles which are not helpful, I figured my entire life was gone. Living without the solutions to the problems you have solved through your post is a serious case, as well as the kind which might have in a negative way damaged my career if I had not noticed your web page. Your own understanding and kindness in touching all the details was vital. I am not sure what I would have done if I had not come upon such a stuff like this. It’s possible to at this moment relish my future. Thanks for your time so much for this high quality and sensible help. I will not think twice to suggest the website to any individual who needs to have guidelines about this issue.

  14. Jamslulk说:

    Doctor, email, archaeological year for way, coverage may unfortunately result in comprehensive organ. Saw palmetto is a cheap generic viagra pills severe online cafergot. buy cialis generic Do not be afraid of low costs and a word Generic. The Indian manufacturers of medications for the ED treatment have a good reputation, and most of them have the advanced equipment to create quality and safe medications.

  15. AlanJaild说:

    [url=https://furosemidepill.com/]furosemide 160 mg daily[/url] [url=https://lisinoprilht.com/]lisinopril 10mg[/url] [url=https://albenzamed.com/]buy albenza[/url] [url=https://hydroxychlorequine.com/]hydroxychloroquine sulfate oral[/url] [url=https://ventolininhl.com/]ventolin[/url] [url=https://ciprorx.com/]where can i buy cipro online[/url] [url=https://lasixsale.com/]lasix 100 mg online[/url] [url=https://zithromaxcov.com/]zithromax capsules australia[/url] [url=https://cozaar24.com/]generic cozaar[/url] [url=https://wellbutrin911.com/]wellbutrin xl 300 mg generic[/url] [url=https://cytotecrx.com/]buy cytotec[/url] [url=https://trazodone911.com/]trazodone medicine[/url] [url=https://prednisolone360.com/]generic prednisolone[/url] [url=https://diflucanf.com/]diflucan prescription cost[/url] [url=https://advairdsk.com/]advair disc[/url] [url=https://lexepro.com/]lexapro 5 mg tablet[/url] [url=https://kamagrabest.com/]kamagra paypal[/url] [url=https://tretinoint.com/]how to buy tretinoin[/url] [url=https://ataraxrx.com/]atarax price[/url] [url=https://finasteride24.com/]buy propecia finasteride[/url]

  16. agen bandarQ说:

    I loved as much as you’ll receive carried out right here.

    The sketch is attractive, your authored material stylish.
    nonetheless, you command get bought an shakiness
    over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this hike.

  17. dominoqq说:

    We’re a group of volunteers and opening a brand new scheme in our
    community. Your site offered us with valuable information to work on. You’ve performed an impressive
    process and our whole community will probably be
    thankful to you.

  18. agen bandarQ说:

    Today, I went to the beach front with my kids.
    I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear. She never wants to go back!
    LoL I know this is totally off topic but I had to tell someone!

  19. KeneUpser说:

    Moyens Eprouves Pour Durer Plus Longtemps Au Lit Jeososmorb [url=https://ascialis.com/#]cialis buy online usa[/url] byboarmalm Cialis Rezeptfrei Gofeminin Feemia Cialis annony Cialis 10mg

发表评论

邮箱地址不会被公开。 必填项已用*标注