In Java, an exception is an abnormal condition or error that occurs during the program execution. These conditions can be caused by unpredictable events such as programming errors, run-time failures, or external problems as hardware failures or network outages.
There are two main types of exceptions in Java:
Checked Exception
These are exceptions that the compiler requires you to handle explicitly, either by handling the exception with a "try-catch" block or by declaring that your method can throw that exception using the "throws" keyword.
Example of a checked exception:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExempleCheckedException {
public static void main(String[] args) {
try {
// code that can throws an exception
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
} catch (FileNotFoundException e) {
// exception treatment
System.out.println("File not found: " + e.getMessage());
}
}
}
Unchecked Exceptions
These are exceptions that the compiler does not require you to handle explicitly. These are typically subclasses of "RuntimeException" and can occur at runtime. Programming errors, such as division by zero or accessing an invalid index in an array, are examples of unchecked exceptions.
Example of an unchecked exception:
public class ExempleUncheckedException {
public static void main(String[] args) {
// code that can throws an unchecked exception
int result = 10 / 0; // this will throw ArithmeticException
}
}
Exception Handling
Exception handling in Java is performed using "try", "catch", "finally" and, optionally, "throws" blocks.
Here is a basic example:
try {
// code that can throws an exception
// ...
} catch (ExceptionType e1) {
// treatment to ExceptionType
// ...
} catch (ExceptionType2 e2) {
// treatment to ExceptionType
// ...
} finally {
// optional block that is always executed, independent of the exceptions
// ...
}
- The "try" block contains code that can throw an exception.
- "Catch" blocks are used to handle specific exceptions. A "catch" block will be executed only if the corresponding exception is thrown in the "try" block.
- The "finally" block is optional and is executed regardless of whether an exception occurs or not. It is often used to perform cleanup actions such as closing files or database connections.
Additionally, the "throws" keyword can be used in a method signature to indicate that the method can throw a specific exception, leaving the handling to the caller of that method.
Nenhum comentário:
Postar um comentário