How to throw exception in java with example
In Java we have already defined exception classes such as ArithmeticException, NullPointerException, ArrayIndexOutOfBounds exception etc. These exceptions are set to trigger on different-2 conditions. For example when we divide a number by zero, this triggers ArithmeticException, when we try to access the array element out of its bounds then we get ArrayIndexOutOfBoundsException.
We can define our own set of conditions or rules and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException when we divide number by 5, or any other numbers, what we need to do is just set the condition and throw any exception using throw keyword. Throw keyword can also be used for throwing custom exceptions, I have covered that in a separate tutorial, see Custom Exceptions in Java.
Syntax of throw keyword:
throw new exception_class("error message");
throw new ArithmeticException("dividing a number by 5 is not allowed in this program");
Example of throw keyword
Lets say we have a requirement where we we need to only register the students when their age is less than 12 and weight is less than 40, if any of the condition is not met then the user should get an ArithmeticException with the warning message “Student is not eligible for registration”. We have implemented the logic by placing the code in the method that checks student eligibility if the entered student age and weight doesn’t met the criteria then we throw the exception using throw keyword.
/* In this program we are checking the Student age * if the student age else < System.out.println("Student Entry is Valid!!"); >> public static void main(String args[]) < System.out.println("Welcome to the Registration process!!"); checkEligibilty(10, 39); System.out.println("Have a nice day.."); >>
Welcome to the Registration process!!Exception in thread "main" java.lang.ArithmeticException: Student is not eligible for registration at beginnersbook.com.ThrowExample.checkEligibilty(ThrowExample.java:9) at beginnersbook.com.ThrowExample.main(ThrowExample.java:18)
In the above example we have throw an unchecked exception, same way we can throw unchecked and user-defined exception as well.
For more examples on throw keyword, refer this: Throw keyword examples.
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
you said that user defined exceptions use throw clause and java defined use throws. but cannot find difference in examples you explained. can you explain it please.
Now I came to know that how We can throw our own custom Exception. I have seen this in our project codebase but never understood but now reading this document, I understand and now I understand my codebase too.
Thanks buddy.
very good work.
really appreciated.
How to Throw Exceptions
Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it’s always thrown with the throw statement.
As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.
You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.
You can also create chained exceptions. For more information, see the Chained Exceptions section.
The throw Statement
All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here’s an example of a throw statement.
throw someThrowableObject;
Let’s look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.
public Object pop() < Object obj; if (size == 0) < throw new EmptyStackException(); > obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; >
The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0 ), pop instantiates a new EmptyStackException object (a member of java.util ) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes. For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.
Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur.
Throwable Class and Its Subclasses
The objects that inherit from the Throwable class include direct descendants (objects that inherit directly from the Throwable class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable class). The figure below illustrates the class hierarchy of the Throwable class and its most significant subclasses. As you can see, Throwable has two direct descendants: Error and Exception .
Error Class
When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error . Simple programs typically do not catch or throw Error s.
Exception Class
Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. Most programs you write will throw and catch Exception s as opposed to Error s.
The Java platform defines the many descendants of the Exception class. These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size.
One Exception subclass, RuntimeException , is reserved for exceptions that indicate incorrect use of an API. An example of a runtime exception is NullPointerException , which occurs when a method tries to access a member of an object through a null reference. The section Unchecked Exceptions The Controversy discusses why most applications shouldn’t throw runtime exceptions or subclass RuntimeException .
Throw exception in java with example
правильно ли понимаю, что когда я работаю с проектом, в котором есть несколько потоков исполнения, может быть вот такая ситуация. Один из этих потоков запускается и завершается успешно, а затем выбрасывает исключение внутри блока try-catch. Оставшиеся потоки исполнения продолжают свою работу, но никакой код в блоке finally не выполняется. Тогда блок finally при обработке исключений не будет выполнен?
я читаю про исключения на 1м и в принципе понимаю, но не очень. ps: зачем только я начал с java core. pss: если вы это читаете, и я до сих пор на первом, то либо я прохожу другой курс, либо читаю книгу по джаве, параллельно проходя этот курс, либо решил взять перерыв на неопределенный срок времени. никогда не сдамся)
Есть подозрение, что так будет правильнее.
обращу внимание на некоторую неточность. цитата «Создание исключения При исполнении программы исключение генерируется JVM или вручную, с помощью оператора throw» в java исключения это тоже объекты поэтому создается исключение так же как объект new Exception. а бросается в программе с помощью оператора throw. обычно эти операции объединяют в одну throw new Exception(«aaa»);
если что я пишу это с 3 уровня. Под конец лекций я читал статью про бафридер, после нашел там ссылку на потоки вводов, а потом чтобы понять что там говориться ввел гугл про исключение и нашел эту статью, спасибо автору, это статья очень помогла. PS если ты читаешь этот комментарий и видишь что у меня нет прогресса(то есть если я все еще на 3 уровне или чуточку больше), то скажи мне, что я нуб и не дошел до 40 лвла