- Exception handling in Java with examples
- What is an exception?
- Exception Handling in Java
- Why we handle the exceptions?
- Why an exception occurs?
- Difference between error and exception
- Types of exceptions
- 1) Checked exceptions
- 2) Unchecked Exceptions
- Frequently used terms in Exception handling
- What topics are covered in the next tutorials
- Top Related Articles:
- About the Author
- Comments
- What are the different ways to print an exception message in java?
- Printing the Exception message
- Example
- Output
- Exception get error message java
Exception handling in Java with examples
Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions. In this guide, you will learn what is an exception, types of it, exception classes and how to handle exceptions in java with examples.
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message.
The good thing about exceptions is that java developer can handle these exception in such a way so that the program doesn’t get terminated abruptly and the user get a meaningful error message.
For example: You are writing a program for division and both the numbers are entered by user. In the following example, user can enter any number, if user enters the second number (divisor) as 0 then the program will terminate and throw an exception because dividing a number by zero gives undefined result. To get the user input, we are using Scanner class. Notice the output of the program.
import java.util.Scanner; public class JavaExample < public static void main(String[] args) < int num1, num2; Scanner scan = new Scanner(System.in); System.out.print("Enter first number(dividend): "); num1 = scan.nextInt(); System.out.print("Enter second number(divisor): "); num2 = scan.nextInt(); int div = num1/num2; System.out.println("Quotient: "+div); >>
As you can see, the user input caused the program to throw Arithmetic exception, however this is not a good programming practice to leave such exceptions unhandled. Let’s handle this exception.
Exception Handling in Java
Here, we are trying to handle the exception that is raised in the above program. You can see that the program ran fine and gave a meaningful error message which can be understood by the user.
Note: Do not worry about the try and catch blocks as we have covered these topics in detail in separate tutorials. For now just remember that the code that can throw exception needs to be inside try block and the catch block follows the try block, where the exception error message is set.
import java.util.Scanner; public class JavaExample < public static void main(String[] args) < int num1, num2; Scanner scan = new Scanner(System.in); System.out.print("Enter first number(dividend): "); num1 = scan.nextInt(); System.out.print("Enter second number(divisor): "); num2 = scan.nextInt(); try < int div = num1 / num2; System.out.println("Quotient: "+div); >catch(ArithmeticException e) < System.out.println("Do not enter divisor as zero."); System.out.println("Error Message: "+e); >> >
If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user.
These system generated messages are not user friendly so a user will not be able to understand what went wrong. In order to let them know the reason in simple language, we handle exceptions. We handle such exceptions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.
Why we handle the exceptions?
Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements, that occur after the statement that caused the exception will not execute and the program will terminate abruptly. By handling we make sure that all the statements execute and the flow of execution of program doesn’t break.
Why an exception occurs?
There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc. Let’s see few scenarios:
1. ArithmeticException:
We have already seen this exception in our example above. This exception occurs when we divide a number by zero. If we divide any number by zero.
int num = 25/0;//ArithmeticException
2. NullPointerException:
When a variable contains null value and you are performing an operation on the variable. For example, if a string variable contains null and you are comparing with another string. Another example is when you are trying to print the length of the string that contains null.
String str = null; //NullPointerException System.out.println(str.length());
3. NumberFormatException:
This exception occurs where there is a type mismatch. Let’s say you are trying to perform an arithmetic operator on a string variable.
String str = "beginnersbook.com"; //NumberFormatException int num=Integer.parseInt(str);
4. ArrayIndexOutOfBoundsException:
When you are trying to access the array index which is beyond the size of array. Here, we are trying to access the index 8 (9th element) but the size of the array is only 3. This exception occurs when you are accessing index which doesn’t exist.
int arr[]=new int[3]; //ArrayIndexOutOfBoundsException arr[8]=100;
Difference between error and exception
Errors indicate that something went wrong which is not in the scope of a programmer to handle. You cannot handle an error. Also, the error doesn’t occur due to bad data entered by user rather it indicates a system failure, disk crash or resource unavailability.
Exceptions are events that occurs during runtime due to bad data entered by user or an error in programming logic. A programmer can handle such conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for example array size is 5 (which means it has five elements) and you are trying to access the 10th element.
Types of exceptions
There are two types of exceptions in Java:
1) Checked exceptions
2) Unchecked exceptions
I have covered these topics in detail in a separate tutorial: Checked and Unchecked exceptions in Java.
1) Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc.
2) Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit.
For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. The examples that we seen above were unchecked exceptions.
Note: Compiler doesn’t enforce you to catch such exceptions or ask you to declare it in the method using throws keyword.
Frequently used terms in Exception handling
try: The code that can cause the exception, is placed inside try block. The try block detects whether the exception occurs or not, if exception occurs, it transfer the flow of program to the corresponding catch block or finally block. A try block is always followed by either a catch block or finally block.
catch: The catch block is where we write the logic to handle the exception, if it occurs. A catch block only executes if an exception is caught by the try block. A catch block is always accompanied by a try block.
finally: This block always executes whether an exception is occurred or not.
throw: It is used to explicitly throw an exception. It can be used to throw a checked or unchecked exception.
throws: It is used in method signature. It indicates that this method might throw one of the declared exceptions. While calling such methods, we need to handle the exceptions using try-catch block.
What topics are covered in the next tutorials
You can read these topics to understand the exception handling concept in detail. You can also practice various programs covered in the following tutorials.
- Try-catch in Java
- Nested Try Catch
- Checked and unchecked exceptions
- Finally block in Java
- try-catch-finally
- finally block & return statement
- Throw exception in Java
- Example of throw keyword
- Example of throws clause
- Throws in Java
- throw vs throws
- Exception handling 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
hi Chaitanya Singh, thanks for your efforts it is really appreciated.this is the best site i have ever seen. very clear explanation. please upload the frameworks also.then it will be very helpful to us.
Hi Chaitanya, Thanks a lot for putting such hard work for us and I can say this is the most simplest website where the beginners really will be start focusing. It helped me and I usually go through your others subject when i get some time.
Am Lecturer in Computer Science, This site is an Excellent site. Very Good Explanation and easy understandable examples. very good. update frequently.
Explanation is good.But, try to give more examples. Examples are so easy. For programming examples should be more for practices.
Same mechanism is used to handle any exception. Difference between checked and unchecked exception is that if you don’t handle checked exception using try…catch block in your program then it will not compile.
Hi Chaitanya, Beginners Book is really one of the best to the ground sites for the basic JAVA learners.
Thanks a lot for it…!!
Compiler error:when we compile the program then we will get compile time error. Exception:an unwanted unexpected event disturbs the normal flow of the program execution.
“When an exception occurs program processing gets terminated and doesn’t continue further.” It is not strictly true… If we handle the exception correctly then it can continue processing.
Am I right? See the first exception of this article:
https://beginnersbook.com/2013/04/try-catch-in-java/
The way you have explained is really awesome, also you have provided the examples where ever required. thanks for your great effort.
Hello Chaitanya, Nice explanation about Exception handling but Could you please elaborate How ClassNotFoundException
comes under the “Checked Exception”, I guess it should be unchecked exception
What are the different ways to print an exception message in java?
An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
Printing the Exception message
You can print the exception message in Java using one of the following methods which are inherited from Throwable class.
- printStackTrace() − This method prints the backtrace to the standard error stream.
- getMessage() − This method returns the detail message string of the current throwable object.
- toString() − This message prints the short description of the current throwable object.
Example
import java.util.Scanner; public class PrintingExceptionMessage < public static void main(String args[]) < Scanner sc = new Scanner(System.in); System.out.println("Enter first number: "); int a = sc.nextInt(); System.out.println("Enter second number: "); int b = sc.nextInt(); try < int c = a/b; System.out.println("The result is: "+c); >catch(ArithmeticException e) < System.out.println("Output of printStackTrace() method: "); e.printStackTrace(); System.out.println(" "); System.out.println("Output of getMessage() method: "); System.out.println(e.getMessage()); System.out.println(" "); System.out.println("Output of toString() method: "); System.out.println(e.toString()); >> >
Output
Enter first number: 10 Enter second number: 0 Output of printStackTrace() method: java.lang.ArithmeticException: / by zero Output of getMessage() method: / by zero Output of toString() method: java.lang.ArithmeticException: / by zero at PrintingExceptionMessage.main(PrintingExceptionMessage.java:11)
Exception get error message java
правильно ли понимаю, что когда я работаю с проектом, в котором есть несколько потоков исполнения, может быть вот такая ситуация. Один из этих потоков запускается и завершается успешно, а затем выбрасывает исключение внутри блока try-catch. Оставшиеся потоки исполнения продолжают свою работу, но никакой код в блоке finally не выполняется. Тогда блок finally при обработке исключений не будет выполнен?
я читаю про исключения на 1м и в принципе понимаю, но не очень. ps: зачем только я начал с java core. pss: если вы это читаете, и я до сих пор на первом, то либо я прохожу другой курс, либо читаю книгу по джаве, параллельно проходя этот курс, либо решил взять перерыв на неопределенный срок времени. никогда не сдамся)
Есть подозрение, что так будет правильнее.
обращу внимание на некоторую неточность. цитата «Создание исключения При исполнении программы исключение генерируется JVM или вручную, с помощью оператора throw» в java исключения это тоже объекты поэтому создается исключение так же как объект new Exception. а бросается в программе с помощью оператора throw. обычно эти операции объединяют в одну throw new Exception(«aaa»);
если что я пишу это с 3 уровня. Под конец лекций я читал статью про бафридер, после нашел там ссылку на потоки вводов, а потом чтобы понять что там говориться ввел гугл про исключение и нашел эту статью, спасибо автору, это статья очень помогла. PS если ты читаешь этот комментарий и видишь что у меня нет прогресса(то есть если я все еще на 3 уровне или чуточку больше), то скажи мне, что я нуб и не дошел до 40 лвла