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));
}
}