
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we have a return statement in the catch or, finally blocks in Java?
Yes, we can write a return statement of the method in catch and finally block.
- There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.
- If we return a value in the catch block and we can return a value at the end of the method, the code will execute successfully.
- If we return a value in the catch block and we can write a statement at the end of the method after return a value, the code will not execute so it became unreachable code as we know Java does not support unreachable codes.
- If we return a value in the final block and no need of keeping a return value at the end of the method.
Example 1
public class CatchReturn { int calc() { try { int x=12/0; } catch (Exception e) { return 1; } return 10; } public static void main(String[] args) { CatchReturn cr = new CatchReturn(); System.out.println(cr.calc()); } }
Output
1
Example 2
public class FinallyReturn { int calc() { try { return 10; } catch(Exception e) { return 20; } finally { return 30; } } public static void main(String[] args) { FinallyReturn fr = new FinallyReturn(); System.out.println(fr.calc()); } }
Output
30
- Related Questions & Answers
- Can we write any statements between try, catch and finally blocks in Java?
- Can a try block have multiple catch blocks in Java?
- What are try, catch, finally blocks in Java?
- Can we have a return statement in a JavaScript switch statement?
- How do we use try...catch...finally statement in JavaScript?
- Can we define a try block with multiple catch blocks in Java?
- Can we have an empty catch block in Java?
- Can we have a try block without a catch block in Java?
- Can finally block be used without catch in Java?
- Flow control in a try catch finally in Java
- What are unreachable catch blocks in Java?
- Will a finally block execute after a return statement in a method in Java?
- Flow control in try catch finally in Java
- Try-Catch-Finally in C#
- When can we use Synchronized blocks in Java?
Advertisements