Java Exceptions

Java Exceptions

Java Exceptions

Java Exceptions:

In Java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. An exception can occur for many reasons, such as invalid input, system failure, or other unexpected conditions. When an exception occurs, Java creates an object called an “exception object” that contains information about the error, such as its type, message, and stack trace.

Java has a built-in mechanism for handling exceptions called “exception handling”. Exception handling allows you to write code that handles exceptions gracefully, instead of allowing the program to crash or produce unexpected results. The basic syntax for exception handling in Java is as follows:

				
					try {
    // code that might throw an exception
} catch (ExceptionType e) {
    // code to handle the exception
}

				
			

Here, the code that might throw an exception is enclosed in a try block, and the code to handle the exception is enclosed in a catch block. If an exception of type ExceptionType is thrown in the try block, control is transferred to the catch block, where you can write code to handle the exception.

There are several types of exceptions in Java, including:

  1. Checked Exceptions – These are exceptions that are checked at compile-time, which means that the compiler will give an error if the exception is not handled. Examples of checked exceptions include IOException, SQLException, and ClassNotFoundException.
  2. Unchecked Exceptions – These are exceptions that are not checked at compile-time, which means that the compiler will not give an error if the exception is not handled. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
  3. Error – These are exceptional conditions that are not recoverable, such as OutOfMemoryError and StackOverflowError. Errors should not be caught and handled by your code.

 

In addition to the try-catch block, there are several other keywords and constructs that are used in exception handling in Java, including:

  1. finally – This keyword is used to specify a block of code that will be executed regardless of whether an exception is thrown or not. This block of code is typically used to clean up resources or perform other finalization tasks.
  2. throw – This keyword is used to explicitly throw an exception from within a method or block of code.
  3. throws – This keyword is used in a method signature to indicate that the method may throw a particular type of exception. This allows callers of the method to handle the exception appropriately.
  4. try-with-resources – This is a special type of try block that is used to automatically close resources (such as files or database connections) when they are no longer needed.

In summary, exceptions are a key aspect of Java programming and provide a mechanism for handling errors and unexpected conditions in a graceful manner. By using exception handling constructs such as try-catch blocks, finally blocks, and throws statements, you can write code that is more robust and resilient to errors.

Here are some examples of Java exceptions and how they can be handled:

  1. Checked Exception: IOException

IOException is a checked exception that is thrown when there is an error in input/output operations. Here is an example of how to handle this exception:

				
					import java.io.*;

public class FileReadExample {
    public static void main(String[] args) {
        try {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
            String line = reader.readLine();
            while (line != null) {
System.out.println(line);
                line = reader.readLine();
            }
reader.close();
        } catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
        }
    }
}

				
			

In this example, we are trying to read the contents of a file called “input.txt”. If an IOException is thrown, we catch it in the catch block and print an error message along with the stack trace.

  1. Unchecked Exception: NullPointerException

NullPointerException is an unchecked exception that is thrown when you try to access a null reference. Here is an example of how to handle this exception:

				
					public class NullPointerExceptionExample {
    public static void main(String[] args) {
        try {
            String str = null;
            int length = str.length();
        } catch (NullPointerException e) {
System.out.println("The string reference is null.");
e.printStackTrace();
        }
    }
}

				
			

In this example, we are trying to get the length of a null string reference. If a NullPointerException is thrown, we catch it in the catch block and print an error message along with the stack trace.

  1. Error: OutOfMemoryError

OutOfMemoryError is an error that is thrown when there is not enough memory available to allocate an object. Here is an example of how to handle this error:

				
					public class OutOfMemoryErrorExample {
    public static void main(String[] args) {
        try {
int[] arr = new int[Integer.MAX_VALUE];
        } catch (Error e) {
System.out.println("An out-of-memory error occurred.");
e.printStackTrace();
        }
    }
} 

				
			

In this example, we are trying to allocate an array with the maximum possible size. If an OutOfMemoryError is thrown, we catch it in the catch block and print an error message along with the stack trace.

  1. Custom Exception: InvalidAgeException

You can also define your own exceptions in Java by extending the Exception or RuntimeException class. Here is an example of a custom exception called InvalidAgeException:

				
					public class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

				
			

You can then use this exception in your code like this:

				
					public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            int age = -5;
            if (age < 0) {
                throw new InvalidAgeException("Age cannot be negative.");
            }
        } catch (InvalidAgeException e) {
System.out.println("An invalid age was entered.");
e.printStackTrace();
        }
    }

				
			

In this example, we are checking if the age entered is negative, and if it is, we throw an InvalidAgeException. If this exception is thrown, we catch it in the catch block and print an error message along with the stack trace.

Overall, exception handling is a key part of writing robust and error-free Java code. By using the appropriate try-catch blocks and exception handling constructs, you can ensure that your code gracefully handles.

Java Catch Multiple Exceptions:

In Java it is possible to catch multiple exceptions using a single try-catch block. Here’s an example:

				
					try {
    // some code that might throw exceptions
} catch (IOException | NullPointerException | ArithmeticException e) {
    // code to handle each of the possible exceptions
}

				
			

In this example, we are using a single try-catch block to catch three different types of exceptions: IOException, NullPointerException, and ArithmeticException. If any of these exceptions are thrown within the try block, the corresponding catch block will handle the exception.

You can also use multiple catch blocks to handle each exception separately, like this:

				
					try {
    // some code that might throw exceptions
} catch (IOException e) {
    // code to handle IOException
} catch (NullPointerException e) {
    // code to handle NullPointerException
} catch (ArithmeticException e) {
    // code to handle ArithmeticException
}

				
			

In this example, we are using multiple catch blocks to handle each exception separately. If an IOException is thrown, the first catch block will handle it; if a NullPointerException is thrown, the second catch block will handle it; and if an ArithmeticException is thrown, the third catch block will handle it.

Note that the catch blocks are evaluated in the order in which they appear, so if an exception matches multiple catch blocks, only the first matching catch block will be executed. Also, when catching multiple exceptions in a single catch block, the exception variable e is implicitly declared as final, so you cannot modify it within the catch block.

 

Join To Get Our Newsletter
Spread the love