The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. The caller must catch the exceptions. If you do not handle the exception in the try-catch block, compiling will fail. But almost every other method in the java library or even user-defined may throw an exception or two.

Java Throw Exception Example

First of all, we need to know about what is an Exception. An exception is a kind of error at the runtime. There are a lot of exceptions in Java-like ArithmeticExceptionNullPointerExceptionArrayIndexOutOfBound exception, etc.

Suppose we are dividing a number by zero, it will not return any compilation error, but it will return runtime error, and it’s under ArithmeticException. Again, if we add a further element in Array beyond its capacity, then it returns the ArrayIndexOutOfBound exception.

We can define our own sets of rules or conditions and throw an exception explicitly using the throw keyword. We can set a condition like dividing by 5 will return ArithmeticException, and we can throw it using the throw keyword. We can also use throw keyword in Custom Exception.

#java #arithmeticexception #nullpointerexception #arrayindexoutofbound

Java Throw Exception Example | Java throw keyword
3.10 GEEK