Difference between try-catch and throw in java

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

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

Please let me know .

8条回答
  •  一生所求
    2020-12-07 10:38

    If you execute the following example, you will know the difference between a Throw and a Catch block.

    In general terms:

    The catch block will handle the Exception

    throws will pass the error to his caller.

    In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().

    public class CatchThrow {
    
    private static void throwsMethod() throws NumberFormatException {
        String  intNumber = "5A";
    
        Integer.parseInt(intNumber);
    }
    
    private static void catchMethod() {
        try {
    
            throwsMethod();
    
        } catch (NumberFormatException e) {
            System.out.println("Convertion Error");
        }
    
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        catchMethod();
    }
    
    }
    

提交回复
热议问题