DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-76 Understanding Exception Handling in Java with Eclipse IDE

Setting Up Java Project in Eclipse

To start working with Java in Eclipse, follow these steps:

1.File → New → Java Project
Provide a project name and click Finish.

2.Java Version
Use Java 21 (or your preferred version).

3.Create Package & Class

  • Navigate to src → New → Package
  • Enter the package name and save
  • Then go to File → New → Class
  • Enter the class name

4.Main Method Shortcut
Use Ctrl + Space inside the class to generate the main method quickly.

5.Generate Getters and Setters
Go to Source → Generate Getters and Setters to quickly manage class properties.

Java Exception Handling Basics

1. try and catch Blocks

try {
    // risky code
} catch (Exception e) {
    // handle error
}
Enter fullscreen mode Exit fullscreen mode

You can catch specific exceptions like NullPointerException or use a general Exception class to catch all exceptions.

Example of a NullPointerException:

Home h = null;
h.string(); // This will throw NullPointerException
Enter fullscreen mode Exit fullscreen mode

2. Calling Methods on Null Objects

When you call methods on objects that haven’t been initialized, you encounter a NullPointerException. For example:

Demo demo = null;
demo.display(); // Throws NullPointerException
Enter fullscreen mode Exit fullscreen mode

Smart Exception Handling Tips

  • Use Superclass in Catch Block: Instead of catching every exception separately, catch their parent class:
  catch (Exception e) {
      e.printStackTrace();
  }
Enter fullscreen mode Exit fullscreen mode
  • Understanding Exception Class:
    In Java, every exception is a subclass of the Throwable class. Use this hierarchy to your advantage.

  • Using throws Keyword:
    If a method does not handle the exception, it must declare it using throws.

  public void readFile() throws IOException {
      // code
  }
Enter fullscreen mode Exit fullscreen mode
  • Can We Throw Objects? You can throw only objects that are instances of Throwable or its subclasses:
  throw new IOException("File not found");
Enter fullscreen mode Exit fullscreen mode
  • User-Defined Exceptions: You can create your own exceptions by extending the Exception class:
  class MyException extends Exception {
      public MyException(String message) {
          super(message);
      }
  }
Enter fullscreen mode Exit fullscreen mode
  • Finally Block: Used for cleanup code that runs regardless of exception occurrence:
  finally {
      // code that runs always
  }
Enter fullscreen mode Exit fullscreen mode

Understanding Java Internals

  • Object is the Parent Class:
    All Java classes by default inherit from the Object class.

  • throw vs throws:

    • throw is used to actually throw an exception.
    • throws is used in method signature to declare exceptions.

-

Top comments (0)