
- 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
What are the rules to follow while using exceptions in java lambda expressions?
The lambda expressions can't be executed on their own. It is used to implement methods that have declared in a functional interface. We need to follow a few rules in order to use the exception handling mechanism in a lambda expression.
Rules for Lambda Expression
- A lambda expression cannot throw any checked exception until its corresponding functional interface declares a throws clause.
- An exception thrown by any lambda expression can be of the same type or sub-type of the exception declared in the throws clause of its functional interface.
Example-1
interface ThrowException { void throwing(String message); } public class LambdaExceptionTest1 { public static void main(String[] args) { ThrowException te = msg -> { // lambda expression throw new RuntimeException(msg); // RuntimeException is not a checked exception }; te.throwing("Lambda Expression"); } }
Output
Exception in thread "main" java.lang.RuntimeException: Lambda Expression at LambdaExceptionTest1.lambda$main$0(LambdaExceptionTest1.java:8) at LambdaExceptionTest1.main(LambdaExceptionTest1.java:10)
Example-2
import java.io.*; interface ThrowException { void throwing(String message) throws IOException; } public class LambdaExceptionTest2 { public static void main(String[] args) throws Exception { ThrowException te = msg -> { // lambda expression throw new FileNotFoundException(msg); // FileNotFoundException is a sub-type of IOException }; te.throwing("Lambda Expression"); } }
Output
Exception in thread "main" java.io.FileNotFoundException: Lambda Expression at LambdaExceptionTest2.lambda$main$0(LambdaExceptionTest2.java:9) at LambdaExceptionTest2.main(LambdaExceptionTest2.java:11)
- Related Questions & Answers
- What are the scoping rules for lambda expressions in Java?
- What are lambda expressions in Java?
- What are block lambda expressions in Java?
- What are the rules to be followed while using varargs in java?
- What are the advantages of Lambda Expressions in Java?
- What are the characteristics of lambda expressions in Java?
- What are the rules we need to follow in JShell in Java 9?
- What are the Rules of Netiquette You Must Follow?
- Are lambda expressions objects in Java?
- What are lambda expressions in C#?
- What are the rules for the body of lambda expression in Java?
- What are lambda expressions and how to use them in Java?
- How to implement the listeners using lambda expressions in Java?
- What are the rules for a local variable in lambda expression in Java?
- What are the rules for formal parameters in a lambda expression in Java?
Advertisements