Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

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 341 views
1 answer 147 views
147 views asked Jul 11, 2022 by avibootz
1 answer 190 views
3 answers 298 views
298 views asked Jan 3, 2016 by avibootz
1 answer 204 views
204 views asked Jun 4, 2021 by avibootz
...