Java is a versatile programming language, and exception handling is one of its key features. In this tutorial, we'll dive into the throw keyword, a powerful tool for handling errors in Java.
throw keyword? 🎯The throw keyword is used to create and throw an exception manually in Java. It allows you to customize error messages and control how exceptions are handled in your code.
Before we dive into the throw keyword, let's briefly recap what an exception is:
checked and unchecked. We'll focus on checked exceptions in this tutorial.throw keyword 💡Now, let's see how to use the throw keyword to create and throw custom exceptions:
Exception:public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}throw keyword to create and throw instances of your custom exception:public class Main {
public static void main(String[] args) {
try {
checkAge(17);
} catch (CustomException e) {
System.err.println(e.getMessage());
}
}
public static void checkAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("The person is underage.");
}
}
}In this example, we created a CustomException class and used it to throw an exception if the provided age is less than 18.
What is the purpose of the `throw` keyword in Java?
Now that you've learned about the throw keyword, let's explore more advanced topics in Java exception handling! Stay tuned to CodeYourCraft for more in-depth tutorials and real-world examples. Happy coding! 💻 🌟