0% found this document useful (0 votes)
81 views

Exceptions in Java

Java has a robust exception handling system that allows code to handle exceptions through try-catch blocks or by throwing exceptions. There are two types of exceptions: checked exceptions which must be caught and handled, and unchecked exceptions which represent program defects. Try-catch blocks catch exceptions in the try block and allow handling code in the catch block. Exceptions can also be explicitly thrown using the throw keyword.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Exceptions in Java

Java has a robust exception handling system that allows code to handle exceptions through try-catch blocks or by throwing exceptions. There are two types of exceptions: checked exceptions which must be caught and handled, and unchecked exceptions which represent program defects. Try-catch blocks catch exceptions in the try block and allow handling code in the catch block. Exceptions can also be explicitly thrown using the throw keyword.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Java has a robust exception handling system that allows you to write code that can handle

various types of exceptions. In this article, we will take a detailed look at how to handle
exceptions in Java.

What are Exceptions in Java?


Exceptions are events that occur during the execution of a program that disrupt the normal flow
of instructions. When an exception occurs, it is said to be "thrown". Java has a rich set of built-in
exception classes that cover most of the common error conditions that can arise.

There are two types of exceptions in Java: checked and unchecked. Checked exceptions are those
that must be caught and handled by the code, while unchecked exceptions are not required to be
caught. Checked exceptions are exceptional conditions that a well-written program should
anticipate and recover from. Unchecked exceptions, on the other hand, represent defects in the
program (bugs) that cannot be recovered from.

The Different Types of Exceptions


In Java, there are two types of exceptions: checked and unchecked. Checked exceptions are those
that must be caught and handled by the code, while unchecked exceptions are not required to be
caught.

Checked exceptions are exceptional conditions that a well-written program should anticipate and
recover from. Examples of checked exceptions include IOException and SQLException. These
exceptions must be caught and handled by the code, or else the program will not compile.

Unchecked exceptions, on the other hand, represent defects in the program (bugs) that cannot be
recovered from. Examples of unchecked exceptions include NullPointerException and
ArrayIndexOutOfBoundsException. These exceptions do not need to be caught and handled by
the code, and the program will continue to run even if they are not caught.

In summary, checked exceptions are exceptional conditions that a well-written program should
anticipate and recover from, while unchecked exceptions represent defects in the program that
cannot be recovered from. It is important to understand the difference between these two types of
exceptions in order to properly handle them in your code.

How to Handle Exceptions in Java


There are two ways to handle exceptions in Java: the first is to use a try-catch block, and the
second is to throw an exception.

Try-Catch Block
The try-catch block is the most common way to handle exceptions in Java. It is used to catch
exceptions that occur during the execution of a program. For example, if you have a file that you
are trying to read from, but it does not exist, you can use a try-catch block to catch the
FileNotFoundException.

To use a try-catch block, you simply put the code that might throw an exception inside the try
block, and then put the code to handle the exception in the catch block. For example:

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

If an exception occurs in the try block, it will be passed to the catch block where it can be
handled. If no exception occurs, then the code in the catch block will never be executed.

It is also possible to specify multiple catch blocks for a single try block. This can be useful if
different exceptions require different handling logic. For example:

try {
// Code that might throw an exception
} catch (FileNotFoundException e) {
// Code to handle the FileNotFoundException
} catch (IOException e) {
// Code to handle the IOException
}

In this example, the try block contains code that might throw either a FileNotFoundException or
an IOException. If a FileNotFoundException occurs, control will jump to the first catch block
and execute the code there. If an IOException occurs, control will jump to the second catch block
and execute the code there.

Finally, it is also possible to use a finally block after a try-catch structure. Code in a finally block
will always be executed, whether or not an exception occurs. This can be useful for cleanup tasks
such as closing files or releasing resources. For example:

try {
// Code that might throw an exception
} catch (Exception e) {
// Code to handle the exception
} finally {
// Cleanup code
}
In this example, the code in the finally block will be executed whether or not an exception occurs
in the try block. This can be used to ensure that resources are properly released, even if an
exception occurs.

Throwing an Exception

In addition to handling exceptions using a try-catch block, it is also possible to throw an


exception explicitly in your code. This can be useful if you want to throw an exception when a
certain condition is met. For example, if you have a method that calculates the square root of a
number, you can throw an IllegalArgumentException if the number is negative.

To throw an exception, you simply use the throw keyword followed by an instance of the
exception class. For example:

if (number < 0) {
throw new IllegalArgumentException("Number must be positive");
}

In this example, if the number is negative, an IllegalArgumentException will be thrown with the
specified error message. The exception can then be caught and handled using a try-catch block,
as described above.

Custom Exceptions

In addition to the built-in exception classes in Java, it is also possible to create your own custom
exception classes. This can be useful if you want to define a specific type of exception that is
specific to your application.

To create a custom exception class, you simply need to extend the Exception class or one of its
subclasses. For example:

public class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

In this example, we have created a custom exception class called CustomException that extends
the Exception class. This class has a constructor that takes a string message and passes it to the
superclass constructor.

Once you have created a custom exception class, you can throw an instance of it using the throw
keyword, just like any other exception. For example:
throw new CustomException("An error has occurred");

Examples of Exception Handling in Java


Here is an example of how to handle exceptions in Java using a try-catch block:

try {
// Code that might throw an exception
int x = 1 / 0;
} catch (Exception e) {
// Code to handle the exception
System.out.println("An exception occurred: " + e.getMessage());
}

In this example, the try block contains code that might throw an exception, in this case,
attempting to divide by zero. If an exception occurs, it will be caught by the catch block and the
code in the catch block will be executed. In this case, the exception message will be printed to
the console.

It is also possible to specify multiple catch blocks for a single try block, as shown in this
example:

try {
// Code that might throw an exception
int x = 1 / 0;
} catch (ArithmeticException e) {
// Code to handle the ArithmeticException
System.out.println("An arithmetic exception occurred: " + e.getMessage());
} catch (Exception e) {
// Code to handle any other exception
System.out.println("An exception occurred: " + e.getMessage());
}

In this example, the try block contains the same code that might throw an exception

Conclusion

In this article, we have seen how to handle exceptions in Java. We looked at the different types
of exceptions and how to use try-catch blocks to handle them. We also saw how to throw an
exception explicitly in your code, and how to create custom exception classes. By using these
techniques, you can write code that is able to handle exceptions gracefully and recover from
error conditions.

You might also like