Java program to handle NoSuchFieldException

Java example to handle NoSuchFieldException.
Submitted by Nidhi, on April 18, 2022

Problem Solution:

In this program, we will handle a NoSuchFieldException using try, catch block. The code that may generate an exception should be written in the try block, and the catch block is used to handle the exception and prevent program crashes.

Program/Source Code:

The source code to handle NoSuchFieldException is given below. The given program is compiled and executed successfully.

// Java program to handle NoSuchFieldException

import java.lang.reflect.*;

public class Main {
  public static void main(String[] args) {
    try {
      String obj = new String();
      Class cls = obj.getClass();

      Field fld = cls.getField("name");
      System.out.println("Field found: " + fld.toString());
    } catch (NoSuchFieldException e) {
      System.out.println("Exception: " + e);
    }

    System.out.println("Program finished");
  }
}

Output:

Exception: java.lang.NoSuchFieldException: name
Program finished

Explanation:

In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program.

Here, we created try and catch blocks. In the try block, NoSuchFieldException gets generated because we tried to access of name field, which is not present in the String class. And, we handled generated exceptions using the catch block and printed exception message.

Java Exception Handling Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.