Search the courses, subjects, tracks, games and features, or jump straight to a page.
Learn it your way
A short class with Sarah and her students. The other ways are under More.
Sign up free to listen. Transcripts are free to read.
So far Java has thrown exceptions for us, for example when we divided by zero. Today we throw our own. The statement is throw new ExceptionType with a message in brackets.
Why do we need the new keyword in there?
An exception is an object, so new creates it and fills in its message. Then throw raises it, right at that line. Only exception objects can be thrown: throwing a plain String will not even compile.
What happens to the lines after the throw?
The rest of the try block, or of the method, is skipped, and Java jumps to the nearest catch block that matches the exception's type. A statement written directly after throw in the same block could never run, so Java will not even compile it. If no catch block matches, the program stops and prints the thread, the exception's class and your message, followed by a stack trace showing where it was thrown.
Like the lesson's output, which names the main thread, then java.lang.ArithmeticException, then our message?
Exactly. Wrap the code in try and catch, though, and the program can report the problem and carry on.
So throw raises the alarm, and a catch block is the safety net that decides what happens next.
The lesson's age check throws an ArithmeticException. Does an age of 15 have anything to do with arithmetic?
Not really. Nothing was divided by zero.
Right. ArithmeticException is meant for arithmetic problems. When a method receives a value it cannot accept, Java has a built-in exception made for exactly that: IllegalArgumentException.
So a method that books tickets could throw IllegalArgumentException when someone asks for 0 tickets?
Perfect. And put the bad value in the message, such as You can book 1 to 6 tickets, not 9, so the error explains itself.
And if a loop is processing many values, I should put the try-catch inside the loop?
Yes, then one bad value is reported and skipped, and the rest are still processed.
So a good message names the rule and the bad value, like Marks must be between 0 and 100, got 105.
The lesson says you can also throw a custom exception. How would we make an UnderageException?
Write a class that extends an existing exception class?
Yes. Extend RuntimeException and give it a constructor that takes the message and passes it to super(message), so getMessage() can return it.
Does the method that throws it need anything special in its header?
Not when it extends RuntimeException. An exception that extends Exception directly (not RuntimeException) is a checked exception: it must be caught or declared with a throws clause, which is the next lesson.
And we catch it like any other exception, with catch (UnderageException e)?
Exactly, and e.getClass().getSimpleName() even tells you the exception's class name.
So for now, extending RuntimeException keeps our methods simple, and the next lesson explains the throws clause for the other kind.
throw new ExceptionType("message"); creates an exception object and raises it at once.
once a throw runs, the rest of the try block (or method) is skipped; a statement written directly after throw in the same block does not even compile.
the nearest matching catch block handles the exception; without one, the program stops.
include the bad value in the message so the error explains itself.
IllegalArgumentException fits a bad method argument better than ArithmeticException.
a class extending RuntimeException can be thrown without a throws clause, while one extending Exception directly (not RuntimeException) is a checked exception and must be caught or declared with throws (lesson 7.11).
The lesson's age check with a try-catch around it. The welcome line is skipped because the throw happens first, but the program reports the problem and keeps running:
public class CaughtUnderage {
public static void main(String[] args) {
int age = 15;
try {
if (age < 18) {
throw new ArithmeticException("You are underaged!");
}
System.out.println("Welcome to the club!"); // skipped when the exception is thrown
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage()); // Caught: You are underaged!
}
System.out.println("The program keeps running.");
}
}ArithmeticException where it really fits: the method throws it with a clear message before an impossible average is calculated, instead of letting Java fail later with the less helpful "/ by zero":
public class SafeAverage {
static int average(int total, int count) {
if (count == 0) {
throw new ArithmeticException("Cannot average zero items");
}
return total / count;
}
public static void main(String[] args) {
try {
System.out.println("Average of 3 scores: " + average(240, 3)); // 80
System.out.println("Average of 0 scores: " + average(0, 0)); // throws
} catch (ArithmeticException e) {
System.out.println("Problem: " + e.getMessage()); // Problem: Cannot average zero items
}
}
}IllegalArgumentException for a bad argument. The message includes the rejected value, and the try-catch sits inside the loop so every request is handled:
public class TicketBooking {
static void orderTickets(int count) {
if (count < 1 || count > 6) {
throw new IllegalArgumentException("You can book 1 to 6 tickets, not " + count);
}
System.out.println("Booked " + count + " ticket(s)");
}
public static void main(String[] args) {
int[] requests = {2, 0, 9, 4};
for (int r : requests) {
try {
orderTickets(r);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
}A custom exception: UnderageException extends RuntimeException, so enterClub needs no throws clause, and getClass().getSimpleName() prints the exception's own class name:
class UnderageException extends RuntimeException {
UnderageException(String message) {
super(message);
}
}
public class ClubEntry {
static void enterClub(String name, int age) {
if (age < 18) {
throw new UnderageException(name + " is " + age + ", which is under 18");
}
System.out.println(name + " may enter");
}
public static void main(String[] args) {
String[] names = {"Kabir", "Meera", "Arjun"};
int[] ages = {21, 16, 19};
for (int i = 0; i < names.length; i++) {
try {
enterClub(names[i], ages[i]);
} catch (UnderageException e) {
System.out.println("Stopped by " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
}Make it with new and raise it with throw; catch it nearby, or the program won't go.
A bouncer checks every guest at the club door. When he spots someone underage, he stops them and raises the alarm with a note saying why: that is throw. The manager on duty reads the note and handles it calmly: that is catch. On a night with no manager, the whole club has to close: that is an uncaught exception stopping the program.
Check, Throw, Catch: check the condition, throw when it fails, and catch where you can deal with it.
T.N.T. - Throw, New, Type, the order of the words in throw new ExceptionType("message").
Term
What is the syntax for manually raising an exception?
Click to flip
Term
What happens to the rest of the try block once a throw runs?
Click to flip
Term
What does an uncaught exception do to the program?
Click to flip
Term
Which built-in exception suits an invalid value passed to a method?
Click to flip
Term
How do you make a custom exception?
Click to flip
Term
Does a custom exception that extends RuntimeException need a throws clause?
Click to flip
The keyword that raises an exception object at a chosen point in the code.
The object created with new, such as new ArithmeticException("message"), that carries the error's type and message.
The text passed to an exception's constructor and returned by its getMessage() method.
A built-in exception meant for arithmetic errors, such as dividing a whole number by zero.
A built-in exception meant for a method that receives an illegal or inappropriate argument value.
An exception class you write yourself by extending an existing exception class.
The parent class of unchecked exceptions; its subclasses can be thrown without a throws clause.
An exception that no catch block handles; it stops the program and prints its class and message, followed by a stack trace showing where it was thrown.
This section discusses how to manually raise exceptions in Java using the 'throw' keyword.
In this section, we focus on the 'throw' keyword in Java, which allows developers to manually raise exceptions, providing control over error handling. An example of raising an ArithmeticException is presented to illustrate its usage.
In Java, exceptions can be raised manually using the throw keyword. This is particularly useful when you want to enforce specific conditions in your code and handle them as exceptions. By raising exceptions manually, you can provide more meaningful error messages to users and enhance the robustness of your application.
throw new ExceptionType("message");, where new creates the exception object and throw raises it.