How to use try, catch, finally and throw exception in class using Java

2 Answers

0 votes
public class Test {  
    void method_a() {  
        try {  
            System.out.println("class Test - method_a()");  
            method_b();  
        }
        catch(Exception e) {  
            System.out.println("method_a() exception: " + e);  
        }  
    }  
        
    void method_b() throws Exception {
        try {  
             System.out.println("class Test - method_b()");  
             method_c();  
        }
        catch(Exception e) {  
             throw new Exception();  
        }  
        finally {  
             System.out.println("finally");  
        }  
    }
    
    void method_c() throws Exception {  
        throw new Exception();  
    }  
      
    public static void main (String args[]) {  
        Test t = new Test();  
        t.method_a();  
    }  
}   



/*
run:

class Test - method_a()
class Test - method_b()
finally
method_a() exception: java.lang.Exception
	
*/

 



answered Oct 5, 2019 by avibootz
0 votes
public class Test {  
    int n;   
    
    public Test(int n) {   
        this.n = n;  
    }  
    
    public int calc() {  
        n = n * 80; 
        System.out.println(n);  
        try {  
            n = n + 400;  
            System.out.println(n);  
            try {  
                n = n / 2;   
                System.out.println(n);  
                throw new Exception();   
            } 
            catch(Exception e) {  
                    n = 999;
            }  
        }
        catch(Exception e) {  
                n = 1111;   
        } 
        finally {  
             System.out.println("finally");  
        }  
        
        return n;  
    }  
          
    public static void main (String args[]) {  
        Test t = new Test(8);  

        System.out.println(t.calc());  
    }  
}    



/*
run:

640
1040
520
finally
999
	
*/

 



answered Oct 5, 2019 by avibootz

Related questions

1 answer 328 views
1 answer 139 views
139 views asked Jul 11, 2022 by avibootz
1 answer 180 views
3 answers 290 views
290 views asked Jan 3, 2016 by avibootz
1 answer 194 views
194 views asked Jun 4, 2021 by avibootz
...