简体   繁体   中英

Exception Handling; Try Catch

Here's my code:

class FinallyDemo {
    static void myMethod(int n) throws Exception{
        try {
            switch(n) {
                case 1: 
                    System.out.println("1st case");
                    return;
                case 3: 
                    System.out.println("3rd case");
                    throw new RuntimeException("3!");
                case 4: 
                    System.out.println("4th case");
                    throw new Exception("4!");
                case 2: 
                    System.out.println("2nd case");
            }
        catch (RuntimeException e) {
            System.out.print("RuntimeException: ");
            System.out.println(e.getMessage());
        } finally {
            System.out.println("try-block entered.");
        }
    }

    public static void main(String args[]){
        for (int i=1; i<=4; i++) {
            try {
                FinallyDemo.myMethod(i);
            } catch (Exception e){
                System.out.print("Exception caught: ");
                System.out.println(e.getMessage());
            }
            System.out.println();
        }
    }
}

Now, doesnt it work this way:

If I have a try and catch block in the method itself then I need not write

method_name(int n) throws Exception ?

Doesnt try-catch block in the method that throws exception prevents from writing "throws exception" in the method that throws exception?

In your example, the case 4 throws an exception while in the catch you are just catching the RuntimeException. Since there is not catch for Exception, your method needs to declare that it throws Exception. If you were to add a catch for Exception, you wouldn't need to throw Exception. This will work.

static void myMethod(int n) {
    try {
        switch (n) {
            case 1:
                System.out.println("1st case");
                return;
            case 3:
                System.out.println("3rd case");
                throw new RuntimeException("3!");
            case 4:
                System.out.println("4th case");
                throw new Exception("4!");
            case 2:
                System.out.println("2nd case");
        }
    } catch (RuntimeException e) {
        System.out.print("RuntimeException: ");
        System.out.println(e.getMessage());
    } catch (Exception e) {
        System.out.print("Exception: ");
        System.out.println(e.getMessage());
    } 
    finally {
        System.out.println("try-block entered.");
    }
}

You don't need the throws clause if and only if the type of exception being thrown is caught (or if it extends RuntimeException . In your case, you throw an Exception with the statement throw new Exception("4!"); , but you only catch the type RuntimeException .

If you add a catch block for Exception , then you will no longer need the throws clause. For example:

static void myMethod(int n) throws Exception{
    try {
        switch(n) {
        case 1: 
            System.out.println("1st case");
            return;
        case 3: 
            System.out.println("3rd case");
            throw new RuntimeException("3!");
        case 4: 
            System.out.println("4th case");
            throw new Exception("4!");
        case 2: 
            System.out.println("2nd case");
        }
    } catch (RuntimeException e) {
        System.out.print("RuntimeException: ");
        System.out.println(e.getMessage());
    } catch(Exception e) {
        System.out.print("Exception: ");
        System.out.println(e.getMessage());
    } finally {
        System.out.println("try-block entered.");
    }
}

Yes, provided you're catching all exception types that can be thrown by the method.

In your code, you throw an Exception but do not supply a catch block for it (you are only catching RuntimeException ), therefore you must declare your method as throwing Exception

You would need:

 ...
 catch (RuntimeException e) {
     System.out.print("RuntimeException: ");
     System.out.println(e.getMessage());
 } catch (Exception e) {
     System.out.print("Exception: ");
     System.out.println(e.getMessage());
 } finally {
 ...

Doesnt try-catch block in the method that throws exception prevents from writing "throws exception" in the method that throws exception?

No, you can always declare to throw exceptions, even if you do not.

Among other things this is useful to allow subclasses to throw them (because they are not allowed to add additional throw clauses). It also allows you to later change the implementation without changing the exception interface.

Right now are tow types of exceptions

  1. Subclasses of Exception.
  2. Subclasess of RuntimeException

The subclasses of Exception are know as checked exception and the compiler ensures that these are managed in try/catch block or through the modifier throws Exception (or subclass) on method.

The subclasess oF RuntimeException are know as unchecked exception and the compile don't require any mechanism for manage it.

Now if you use the modifier throws Exception (or subclass) on a method the compiler will require you manage it with try/catch.

Since you throw both a RuntimeException and an Exception in the switch, you either need to catch both or the method needs to throw the Exception so it can be handled in the method calling myMethod

To catch both use:

catch (RuntimeException e) {
        System.out.print("RuntimeException: ");
        System.out.println(e.getMessage());
}catch (Exception e) {
        System.out.print("Exception: ");
        System.out.println(e.getMessage());
}

Make sure the catch of Exception is always last, otherwise it will also catch the RuntimeException since it extends Exception

You are handling the exception in TWO ways. Firstly if you extend the directly call the Exception class as you have done when declaring the method

method_name(int n) throws Exception

What this means is that no matter what type of exception occurs in the method it will always be able to catch it, For example if an Arithmetic Exception or a NullPointerException or an ArrayIndexOutOfBoundsException occurs inside the method your above declaration will be able to catch each and every one of them. Because of that there is no actual purpose of having the try catch block as well placed inside that method because even RunTimeException is part of the Exception Class hierarchy. Therefore if I understood your question correctly the program will execute and then catch the exception from the catch block, failing which it will catch it from the method declaration. Hope it answers your query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM