Why is “throws Exception” necessary when calling a function?

后端 未结 8 1759
借酒劲吻你
借酒劲吻你 2020-11-29 15:37
class throwseg1
{
    void show() throws Exception
    {
        throw new Exception(\"my.own.Exception\");
    }

    void show2() throws Exception  // Why throws i         


        
8条回答
  •  执念已碎
    2020-11-29 15:47

    package javaexception;
    
    
    public class JavaException {
       void show() throws Exception
        {
            throw new Exception("my.own.Exception");
        }
    
    void show2() throws Exception  // Why throws is necessary here ?
    {
        show();
    }
    
    void show3() throws Exception  // Why throws is necessary here ?
    {
        show2();
    }
    public static void main(String[] args) {
    
       JavaException a = new JavaException();
    
       try{
       a.show3();
       }catch(Exception e){
           System.out.println(e.getMessage());
       }
    }
    

    Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.

提交回复
热议问题