2

As per the new features provided by JAVA 8, the optional class is a way to prevent the null pointer exception. Using the orElseThrow Method() we can throw an exception if the output is null. I want to know how can we throw User Defined exceptions using it

package com.wipro.java8;

import java.util.Optional;

class employee{  
      int id;  
      String name;
      String adress ;
      int salary;  
      employee(int id,String name,String adress,int salary){  
       this.id=id;  
       this.name=name;  
       this.adress=adress ;
       this.salary=salary;  
      }  
    }

class InvalidEmployeeException extends Exception{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    int a;
       InvalidEmployeeException(int b) {
         a=b;
       }
       public String toString(){
         return ("Exception Number =  "+a) ;
      }
    }
public class oc3 {

    public static void main(String[] args) {
        employee e1= new employee(0, null, null, 0);
        Optional<String> n = Optional.ofNullable(e1.name); 
        System.out.print( n.orElseThrow( InvalidEmployeeException ::new));
    }

}
Holger
  • 285,553
  • 42
  • 434
  • 765
  • Does this help? https://stackoverflow.com/questions/36563400/use-of-constructor-reference-where-constructor-has-a-non-empty-parameter-list – Abra Jul 08 '20 at 05:50
  • `n.orElseThrow( InvalidEmployeeException ::new)` This syntax is also fine but you need to overload constructors by introducing no-argument constructor. – Tayyab Razaq Jul 08 '20 at 19:53

1 Answers1

2

If you need to use an exception constructor with arguments, use a lambda expression instead of method reference.

For example:

n.orElseThrow(() -> new InvalidEmployeeException(1))

(P.S. I don't know what the int passed to the exception constructor means, and how you decide which value to pass)

Eran
  • 387,369
  • 54
  • 702
  • 768