DEV Community

velvizhi Muthu
velvizhi Muthu

Posted on

Module 5-Exception handling

01. What is Exception handling?

Exception handling in Java is a mechanism to handle runtime errors (exceptions) and maintain the normal flow of the application.

02. What is an Exception?
An exception is an unexpected event that occurs during the execution of a program and disrupts its normal flow.

03. What is the Throwable?
-superclass(Parent class) of all errors and exceptions in Java.
-Base class for all throwable objects

  1. class name for Throwable? -Error -Exceptions subclass of exceptions: -Checked exceptions -Unchecked exceptions.

05. What is the Error?
Serious problem,the application should not try to handle.

Example:
OutOfMemoryError, StackOverflowError.

OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot allocate enough memory for the application.

StackOverflowError: It is thrown when the stack memory is exhausted due to excessive recursion.

06. What are the checked exceptions?
-Checked exceptions, also known as compile-time errors.
-A compile-time error happens when you write wrong code that the Java compiler cannot understand.
-It is detected before running the program(during compilation)
-The program will not start execution until you fix it.

Example:
Input/output failure
Forgot a semicolon, misspelt a keyword.

07. What are the Unchecked Exceptions?
-Runtime Exceptions.
-Unchecked exceptions occur at runtime and are not checked by the compiler.
-They usually represent programming errors such as logic mistakes.

*Example: *
NullPointerException
Happens when trying to use a null reference.

Ex program:
public class Example {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // Throws NullPointerException
}
}

ArithmeticException: Arithmetic operation takes place, like division by zero.
Example:**

public class Example {
public static void main(String[] args) {
int result = 10 / 0; // Throws ArithmeticException
}
}

Exception handling keywords:
-Try
-Catch
-Finally
-Throw
-Throws

Try block:
The code that might throw an exception is placed inside a try block.

Catch block:
Code inside a catch block handles the specific exception thrown by the try block.

Finally:

  1. The "finally" block is used to execute the necessary code of the program.
    1. It is executed whether an exception is handled or not.

Throw:

  1. Throw is a Java keyword.
  2. The "throw" keyword is used to throw an exception.
  3. The throw keyword is followed by an instance of Exception to be thrown.
  4. The keyword throw is used within the method.

Throws:

  1. The "throws" keyword is used to declare exceptions.
  2. It specifies that an exception may occur in the method.
  3. It doesn't throw an exception.
  4. It is always used with a method signature.

Top comments (0)