In this tutorial, we will learn how to throw and propagate exceptions in Java. An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Goals:
- Understand what exceptions are
- Learn how to manually throw exceptions
- Understand how exception propagation works
- Learn how to control the propagation of exceptions
You will learn how to:
- Use the throw
keyword
- Understand the throws
keyword
- Propagate exceptions
- Handle exceptions
Prerequisites:
To get the most from this tutorial, you should have basic knowledge of Java programming, particularly functions and control flow.
In Java, exceptions are thrown using the throw
keyword. After the throw
keyword, an instance of an exception class is written. This can be an instance of an existing exception class, like ArithmeticException
, or a custom exception class that you create.
Example:
throw new ArithmeticException("Dividing by zero!");
In Java, checked exceptions need to be declared in the method signature if they can be thrown and are not caught within the method. This is done using the throws
keyword.
Example:
public void myMethod() throws IOException {
// code that may throw IOException
}
In this example, we will throw an ArithmeticException
when a division by zero is attempted.
public class Main {
public static void main(String[] args) {
try {
int result = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
return a / b;
}
}
In this example, we will propagate an IOException
from a method to the main function.
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
readFromFile("nonexistent_file.txt");
} catch (IOException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
public static void readFromFile(String fileName) throws IOException {
File file = new File(fileName);
FileReader fr = new FileReader(file);
}
}
throw
keyword.throws
keyword.To learn more about exceptions, you can check out the Java Documentation.
NullPointerException
when a null argument is passed.IOException
.ArithmeticException
and rethrows it as a IllegalArgumentException
.Remember, the best way to learn is by doing. Practice these exercises and experiment with different cases to fully understand exception handling in Java.