The compiler is not executing the catch
part when no value is entered:
import java.util.Scanner;
import java.lang.*;
public class Ruff {
public static void main(String[] args)
{
String a;
Scanner scanf=new Scanner(System.in);
System.out.println("Enter your name!!");
a=scanf.nextLine();
try
{
if(a.toLowerCase().equals("Harsh"))
{
System.out.print("Good Name");
}
else
{
System.out.print("Ok!");
}
}
catch(Exception e)
{
System.out.print("Name Required");
}
}
}
The only possible exception for a
in the code is a NullpointerException
, but a
is the empty string not a null pointer If the user enters no value. You should check for that value instead of using exceptions:
if(a.equals("")) {
System.out.print("Name Required");
}
else {
// code of try block here ...
}