×

Java Programs

Java Practice

Java program to handle NoSuchMethodException

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

Problem statement

In this program, we will handle a NoSuchMethodException using the 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.

Source Code

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

// Java program to handle NoSuchMethodException.

import java.lang.reflect.Method;

public class Main {
  public static void main(String[] args) {
    try {
      Class c = Class.forName("java.lang.String");

      Class[] params = new Class[1];
      Method m = c.getDeclaredMethod("sampleMethod", params);
    } catch (ClassNotFoundException e) {
      System.out.println("Exception1: " + e);
    } catch (NoSuchMethodException e) {
      System.out.println("Exception2: " + e);
    }

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

Output

Exception2: java.lang.NoSuchMethodException: java.lang.String.sampleMethod(null)
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, NoSuchMethodException gets generated because we tried to access of sampleMethod() method, 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.