Using try-catch java

前端 未结 4 1623
甜味超标
甜味超标 2020-12-07 03:08

So just got into the basics of try-catch statements in Java and I\'m still a bit confused on some differences within the syntax.

Here is the code I\'m trying to anal

4条回答
  •  独厮守ぢ
    2020-12-07 03:50

    There are two types of exceptions

    1) Unchecked. These are defined by the Error and RuntimeException classes and all of their subclasses. Java does not force you to handle these exception in any way.

    2) Checked. These are defined be the Throwable class and all of its subclasses that do not fall into the category defined in (1). Java forces you to handle these exceptions with a try/catch. If you call a method that can throw such an exception (defined with the throws keyword) outside of a try block your code will not compile.

    throws : This is a way of declaring that a method can potentially throw an exception that must be caught with a try/catch. For example

    public void doSomething() throws MyException { ... }
    

    is a declaration of a method that can potentially throw an instance of MyException.

    try/catch/finally : This is a way of handling exceptions that may be produced by some sort of code. The cody you are trying to run goes in the try block, the error handling code goes into the catch block. The optional finally block is something that will be executed regardless of whether or not an exception is thrown. In fact the finally block will be called even if you do a return inside your try or your catch. For example

    try {
        doSomething();
    } catch (MyException exception) {
        exception.printStackTrace();
    }
    

    or an example of using finally :

    MyResource myResource = getMyResource();
    try {
        myResource.open();
        doStuffWithMyResource(myResource);
    } catch (Exception exception) {
        exception.printStackTrace();
    } finally {
        if (myResource.isOpen()) {
            myResource.close();
        }
    }
    

提交回复
热议问题