Exception Handling in Java with Examples

Exception Handling in Java with Examples

Exception Handling in Java

Exception handling in Java allows developers to deal with unexpected issues or errors that may occur during program execution.

What is an Exception in Java?

  • An exception in Java is an event that occurs during the execution of a program, disrupting the normal flow of instructions.
  • It represents an error or an unexpected situation that needs to be handled.
  • Exceptions can occur for various reasons, such as invalid input, file not found, or division by zero.

Difference between an Error and an Exception in Java

Errors are usually caused by things outside the program's control, like running out of memory or the computer crashing.
Exceptions are things the program can anticipate, like trying to divide a number by zero or reading a file that doesn't exist.

Types of Exception Handling in Java

  • Java Checked Exceptions
  • Java Unchecked Exceptions
  • Java User-Defined Exceptions

Java Checked Exceptions

  • Checked exceptions are a category of exceptions that are checked by the compiler at compile-time.
  • These exceptions are typically associated with external factors or conditions that a program might encounter during its execution.
  • Some examples are "IOException" and "SQLException".
Loading…

Java Unchecked Exceptions

  • Unchecked exceptions are a category of exceptions that are not checked at compile-time.
  • Also known as runtime exceptions, these exceptions are subclasses of the RuntimeException class.
  • Unchecked exceptions can occur without prior notice and do not require explicit handling.
  • Examples include 'NullPointerException' and 'ArrayIndexOutOfBoundsException.'
Loading…

Java User Defined Exceptions

  • In addition to using predefined exceptions, Java allows the creation of custom exceptions by extending the Exception class.
  • These user-defined exceptions enable the design of unique and tailored classes to address specific application needs.

Step 1 Create a Custom Exception Class

Loading…
  • Here, we create a custom exception class named MyCustomException by extending the built-in Exception class.
  • The custom exception class includes a constructor that accepts a custom error message and passes it to the constructor of the parent Exception class using super(message).

Step 2 Create a Method that May Throw the Custom Exception

Loading…
  • In this step, we define a method named checkAge that takes an integer parameter representing a person's age.
  • We use the throws MyCustomException declaration to indicate that this method may throw our custom exception.
  • Inside the method, we check if the provided age is less than 18. If it is, we throw our custom exception with a specific error message.
  • If the age condition is not met, we print a message indicating that access is granted.

Step 3 Exception Handling

Loading…
  • In the main method, we initialize a variable userAge with a value (you can change this value to test different scenarios).
  • Inside a try-catch block, we call the checkAge method, passing the userAge as an argument.
  • If the checkAge method throws our custom exception due to the age condition, the catch block will execute.
  • In the catch block, we handle the custom exception by displaying a custom error message indicating that access is denied.

try catch Exception handling in Java

  • try: A try block is used to catch exceptions that might arise within its scope.
  • Catch: When an exception is thrown, the program flow jumps to the corresponding catch block, allowing for proper exception handling.
  • throw: The throw keyword is employed to specify an exception under certain conditions, allowing for controlled error propagation.
Loading…
  • finally: The finally block acts as a safety net for code that must run regardless of whether an exception occurs. It's often used to perform cleanup tasks, such as closing resources.
Loading…

How Does JVM Handle an Exception

  • Java Virtual Machine (JVM) plays a crucial role in handling exceptions. When an exception occurs, the JVM looks for a block of code that can handle it.
  • This block of code is known as a 'catch' block. If the JVM finds a matching 'catch' block, it transfers control to that block for further processing.

Pros of Exception Handling

  • Separation of Concerns - Exception handling separates error-handling code from standard program logic. This enhances code readability and maintainability.
  • Debugging Aid: - Exceptions provide valuable information about the cause of an error, including a stack trace that shows where the error occurred.

Cons of Exception Handling

  • Complexity - Handling exceptions can lead to complex code structures, especially in programs with extensive error-checking and multiple try-catch blocks.
  • Overuse - Overusing exceptions for control flow, also known as "exception abuse," can lead to poor coding practices.

Conclusion

Exception handling in Java is vital for robust applications. Differentiate between checked and unchecked exceptions, use user-defined exceptions, and apply try, catch, throw, and finally for graceful error handling and smooth code execution.