types of exception in java with examples

Sandra 109 Published: 07/21/2024

types of exception in java with examples

I'd be happy to explain the types of exceptions in Java with examples!

Java provides several types of exceptions that can be thrown by a program. Exceptions are used to handle runtime errors and abnormal conditions.

Here's a list of the main types of exceptions:

Checked Exceptions: These exceptions are checked at compile-time, meaning that you must explicitly catch them or declare them in your method's throws clause. Examples of checked exceptions include IOException, SQLException, and NetworkException.

Example:

    import java.io.*;

public class Test {

public static void main(String[] args) {

try {

File file = new File("test.txt");

FileReader reader = new FileReader(file);

char[] buffer = new char[10];

reader.read(buffer);

System.out.println(new String(buffer));

} catch (IOException e) {

System.out.println("Caught an IO exception: " + e.getMessage());

}

}

}

Unchecked Exceptions: These exceptions are not checked at compile-time and can be thrown anywhere in a program. Examples of unchecked exceptions include ArithmeticException, NullPointerException, and ClassCastException.

Example:

    public class Test {

public static void main(String[] args) {

try {

int i = Integer.parseInt("test");

System.out.println(i);

} catch (NumberFormatException e) {

System.out.println("Caught an NumberFormat exception: " + e.getMessage());

}

}

}

Error Exceptions: These exceptions are thrown by the JVM itself and can't be caught or declared in a method's throws clause. Examples of error exceptions include OutOfMemoryError, StackOverflowError, and SecurityException.

Example:

    public class Test {

public static void main(String[] args) {

try {

int i = 1 / 0; // will throw an ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Caught an Arithmetic exception: " + e.getMessage());

}

}

}

RuntimeException: These are a type of unchecked exception and can be thrown anywhere in your program.

Example:

    public class Test {

public static void main(String[] args) {

try {

throw new RuntimeException("This is a runtime exception");

} catch (Exception e) {

System.out.println("Caught an Exception: " + e.getMessage());

}

}

}

Exception: This is the parent class for all exceptions in Java.

Example:

    public class Test {

public static void main(String[] args) {

try {

throw new Exception("This is an exception");

} catch (Exception e) {

System.out.println("Caught an Exception: " + e.getMessage());

}

}

}

In summary, the types of exceptions in Java are:

Checked Exceptions Unchecked Exceptions Error Exceptions RuntimeExceptions Exception

Each type has its own use and is used to handle different situations.

How many types of exceptions are there in java with examples

I'll respond in English since you specifically asked for it.

Java has several types of exceptions that can be thrown during the execution of a program. Here's an overview of the most common types:

1. Checked Exceptions

Checked exceptions are those that must be explicitly handled by the programmer using try-catch blocks or by declaring them in the method signature using throws. Examples include:

IOException (when working with files, networks, or I/O operations) SQLException (when interacting with databases) ParseException (when parsing text formats like XML or JSON)

Example: public void readFile(String file) throws IOException { ... }

2. Unchecked Exceptions

Unchecked exceptions, also known as runtime exceptions, are those that can be thrown at any time during the execution of a program and are not required to be handled explicitly by the programmer. Examples include:

NullPointerException (when trying to access an object's field or method without checking for null) ArrayIndexOutOfBoundsException (when accessing an array element beyond its bounds)

Example: String name = null; System.out.println(name.length()); // throws NPE

3. Error Exceptions

Error exceptions are a type of unchecked exception that indicates a severe problem, such as:

OutOfMemoryError (when the JVM runs out of memory)

StackOverflowError (when the method call stack overflows)

Example: try { String str = new String(new byte[Integer.MAX_VALUE]); } catch (OutOfMemoryError e) {}

4. Runtime Exceptions

Runtime exceptions are a type of unchecked exception that can occur during the execution of a program, such as:

ArithmeticException (when performing an invalid arithmetic operation) ClassCastException (when trying to cast an object to an incompatible class)

Example: int x = 5 / 0; // throws ArithmeticException

5. Logic Exceptions

Logic exceptions are not officially recognized by the Java Language Specification but can be considered as a type of unchecked exception that occurs due to logical errors or inconsistencies in the program, such as:

IllegalStateException (when an operation is performed on an object in an invalid state) ConcurrentModificationException (when multiple threads concurrently modify the same data structure)

Example: List<String> list = new ArrayList<>(); list.add(null); // throws NPE when accessing

These are just a few examples of the many types of exceptions that can be thrown in Java. Understanding how to handle and throw exceptions is crucial for writing robust and reliable programs.

(Note: I'll make sure to keep my responses concise and not exceed 300 words.)