Difference between try-catch and throw in java

前端 未结 8 438
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 10:02

What is the difference between try-catch and throw clause. When to use these?

Please let me know .

8条回答
  •  -上瘾入骨i
    2020-12-07 10:39

    try block contains set of statements where an exception can occur.

    catch block will be used to used to handle the exception that occur with in try block. A try block is always followed by a catch block and we can have multiple catch blocks.

    finally block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.

    throw keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.

    throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

    // Java program to demonstrate working of throws, throw, try, catch and finally.

     public class MyExample { 
          
            static void myMethod() throws IllegalAccessException 
            { 
                System.out.println("Inside myMethod()."); 
                throw new IllegalAccessException("demo"); 
            } 
          
            // This is a caller function  
            public static void main(String args[]) 
            { 
                try { 
                    myMethod(); 
                } 
                catch (IllegalAccessException e) { 
                    System.out.println("exception caught in main method."); 
                }
                finally(){
                    System.out.println("I am in final block.");
                } 
            } 
        } 
    

    Output:

    Inside myMethod().
    exception caught in main method.
    I am in final block.
    

提交回复
热议问题