Table of Contents
Exceptions are interruptions in the normal flow of program thanks to an error and other exceptional issue. If you don't handle it properly, it can cause your entire program to terminate and output an error.
Examples of when exceptions can occur:
- when a divide by zero operation was attempted
- a network connection being interrupted
- a user entering incorrect data
In this lesson, we'll learn how to safely and gracefully handle an exception so that your program can continue running properly.
We're trying to prevent this from happening.
Try Catch block
Exceptions in Java are handled using the try-catch
block. The try
block is where the code that could throw an exception is run, whereas the catch
block is the code that you want to run if an exception is indeed thrown.
This is the format for catching exceptions:
JAVAtry {
// code to try
} catch(Exception e) {
// code to handle exception
}
Now let's look at a basic example:
JAVApublic class Main {
public static void main(String[] args) {
try {
int test = 1 / 0;
} catch(ArithmeticException e) {
System.out.println(e);
}
}
}
BASHjava.lang.ArithmeticException: / by zero
Finally block
When you want to run code no matter if an exception was thrown or not, you can use the finally
block:
JAVApublic class Main {
public static void main(String[] args) {
try {
int test = 1 / 0;
} catch(ArithmeticException e) {
System.out.println("An ArithmeticException was thrown!");
} finally {
System.out.println("Moving on!");
}
}
}
BASHAn ArithmeticException was thrown!
Moving on!
Multiple Exceptions
You can handle multiple exceptions by chaining the catch
blocks:
JAVApublic class Main {
public static void main(String[] args) {
try {
String str = null;
str.length();
} catch(ArithmeticException e) {
System.out.println("An ArithmeticException was thrown!");
} catch(NullPointerException e) {
System.out.println("A NullPointerException was thrown!");
} finally {
System.out.println("Moving on!");
}
}
}
BASHA NullPointerException was thrown!
Moving on!
In the above code, we have defined multiple catch
blocks and the correct one was ran when that exception was thrown.
Throwing an Exception
You can throw an exception by using the throw
keyword:
JAVApublic class Main {
public static void main(String[] args) {
try {
throw new NullPointerException("NULL");
} catch(NullPointerException e) {
System.out.println("A NullPointerException was thrown!");
} finally {
System.out.println("Moving on!");
}
}
}
BASHA NullPointerException was thrown!
Moving on!
We can throw our own exceptions! Now if you're wondering why this is useful, well, you can use exceptions to ensure that things in your program are progressing correctly, like this:
JAVApublic class Main {
static void checkMoney(int money) {
if (money < 200) {
throw new ArithmeticException("You must have at least $200.");
} else {
System.out.println("You have enough money!");
}
}
public static void main(String[] args) {
int money = 100;
checkMoney(money);
}
}
BASHException in thread "main" java.lang.ArithmeticException: You must have at least $200.
at Main.checkMoney(Main.java:5)
at Main.main(Main.java:14)
Now that the method checkMoney
can throw an exception of its own, you can choose to handle it like any other risky piece of code:
JAVApublic class Main {
static void checkMoney(int money) {
if (money < 200) {
throw new ArithmeticException("You must have at least $200.");
} else {
System.out.println("You have enough money!");
}
}
public static void main(String[] args) {
int money = 100;
try {
checkMoney(money);
} catch(ArithmeticException e) {
System.out.println("You must have at least $200.");
}
}
}
BASHYou must have at least $200.
Not only is that a much cleaner output, but you can fully control it entirely, and even run more code if needed.
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js