
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Write Code After Throw Statement in Java
No, we can not place any code after throw statement, it leads to compile time error Unreachable Statement.
Throw keyword in Java
- The throw keyword is used to throw an exception manually.
- Whenever it is required to suspend the execution of the functionality based on the user-defined logical error condition, we will use this throw keyword to throw an exception.
- We need to handle these exceptions using try and catch blocks.
Rules to use throw keyword in Java
- The throw keyword must follow Throwable type of object.
- The throw keyword must be used only in the method logic.
- Since it is a transfer statement, we cannot place statements after throw statement. It leads to a compile-time error Unreachable code.
- We can throw user-defined and predefined exceptions using throw keyword.
Example
public class ThrowKeywordDemo { public static void main(String[] args) { try { throw new ArithmeticException(); System.out.println("In try block"); // compile-time error, unreachable statement } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } }
The above code doesn't execute because there is a statement after a throw statement in the try block, it can cause the compile-time error. So we cannot put any statements after a throw statement in Java.
Output
unreachable statement System.out.println("In try block");
Advertisements