Exceptions are unexpected, errors, bugs or events that cause hindrance to the normal execution of a program or may cause a program to crash. To cater to that, there is a very common feature in almost every programming language called exception handling. It enables developers to manage the errors caused by the exceptions in runtime to prevent the crashing of a program.
Table of Contents
In this article, we will be different types of exceptions in Java with their examples.
See Also: Common Java Errors And How To Avoid Them
As java offers a variety of features, it increases the types of mistakes made by developers making them encounter different types of exceptions in java. To make things manageable, we will be classifying all the different types of exceptions in java.
Exceptions can be primarily categorized into two types:
Checked exceptions also known as compile-time exceptions are checked by the compiler during the compilation to confirm whether the exception is already handled or not. If it is not handled by the user, as a result, the system displays a compilation error. SQLException, IOException, and ClassNotFoundException are some Checked exceptions. In the example below, the exceptions are not handled at all to demonstrate the respective output. When you encounter an exception, it also mentions all the different types of exceptions that are thrown.
See this code below demonstrating the checked exception:
01. import java.io.*; 02. class checkedException_demo { 03. public static void main(String args[]) { 04. FileInputStream readFromFile = null; 05. readFromFile = new FileInputStream("C:UsersShaharyarDocumentsmyfile.txt"); 06. // as the file is intentionally not present at this location. It will throw a checked exception 07. int num; 08. // The read() of FileInputStream will also throw a checked exception 09. while(( num = input.read() ) != -1) { 10. System.out.print((char)num); 11. } 12. input.close(); 13. } 14. }
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: Unhandled exception type FileNotFoundException Unhandled exception type IOException Unhandled exception type IOException
Following are some examples of the unchecked type of exceptions in Java:
This type of exception is encountered when dealing with SQL queries on a database. The common causes are unsuccessful connection establishment with the database, incorrect table names, data not present in the tables etc.
Consider the following code example:
01. public void setCustomerInfo(String name, String value) throws SQLClientInfoException { 02. try { 03. checkClosed(); 04. ((java.sql.Connection) this.mc).setcustomerInfo(name, value); 05. } catch (SQLException sqlExe1) { 06. try { 07. checkAndFireConnectionError(sqlExe1); 08. } catch (SQLException sqlExe2) { 09. SQLClientInfoException customer_Ex = new SQLClientInfoException(); 10. customer_Ex.initCause(sqlExe2); 11. throw customer_Ex; 12. } 13. } 14. }
This code will generate an SQLException if the database is not found.
This exception is faced while using I/O stream operations. It is thrown when an input-output operation fails or is interrupted during the execution. If the mentioned input or output source is not found it will result in an I/O exception.
Consider the following code snippet:
01. import java.io.*; 02. public class IO_Exception_Example { 03. private static String filepath = "C:UsershaharyarDesktopmyFile.txt"; 04. public static void main(String[] args) { 05. BufferedReader bufferReader = null; 06. String input; 07. try { 08. bufferReader = new BufferedReader(new FileReader(filepath)); 09. while ((input = bufferReader.readLine()) != null) { 10. System.out.println(input); 11. } 12. } catch (IOException e) { 13. System.err.println("I/O Exception is detected :" + e.getMessage()); 14. } 15. } 16. }
“I/O Exception is detected: ” will be printed on the screen along with the error.
This code will generate an I/O Exception if the file, a source of input in this case is not present in the mentioned directory.
ClassNotFoundException is thrown when the JVM cannot locate a required class. It can be due to a classpath issue, a missing .class file or maybe a command-line error.
See the following code demonstration of ClassNotFoundException:
01. public class ClassNotFoundException_Example { 02. private static final String classToLoad = "main.java.Utils"; 03. public static void main(String[] args) { 04. try { 05. Class loadedClass = Class.forName(classToLoad); 06. System.out.println("Class " + loadedClass + " found!"); 07. } catch (ClassNotFoundException ex) { 08. System.err.println("ClassNotFoundException is present: " + ex.getMessage()); 09. ex.printStackTrace(); 10. } 11. } 12. }
This code will generate a ClassNotFoundException when the class “main.java.Utils” is unavailable. The exception will be thrown with this message, “ClassNotFoundException is present”.
The unchecked exceptions also known as runtime exceptions are the ones that are encountered during the execution of the program. These exceptions cannot be checked during the compilation of the program as it often requires input from the user or an external source. For example, programming bugs like logical errors, incorrect inputs and using incorrect APIs.
To properly understand the unchecked exception, consider this following code demonstration:
01. import java.util.Scanner; 02. public class RunTimeException_Example { 03. public static void main(String[] args) { 04. // Reading the input from user 05. Scanner user_input = new Scanner(System.in); 06. System.out.print("Enter your three digit ID: "); 07. int id = user_input.nextInt(); 08. if (id>0 AND id<1000) { 09. System.out.println("please wait for confirmation"); 10. } else { 11. System.out.println("The entered Id is invalid."); 12. } 13. } 14. }
Output 1:
Enter your three digit ID: 241 Please wait for confirmation
Output 2:
Enter your three-digit ID: two eight four Exception in thread “main” java.util.InputMismatchException at java.util.Scanner.throwFor (Unknown Source) at java.util.Scanner.next (Unknown Source) at java.util.Scanner.nextInt (Unknown Source) at java.util.Scanner.nextInt (Unknown Source) at exceptiondemo.sample_runtimedemo.main(Sample_RunTimeExceptionDemo.java:11)
Following are some of the different types of unchecked exceptions in Java:
This exception occurs when a user tries to access an object using a reference variable which currently is empty.
For example, see the following code:
01. class SampleNullPointer_Example { 02. public static void main(String args[]) { 03. try { 04. String str = null; // this variavle is empty (null value) 05. System.out.println(str.charAt(2)); 06. } catch(NullPointerException e) { 07. System.out.println("NullPointerException is detected."); 08. } 09. } 10. }
NullPointerException is detected.
As the string str is empty, it cannot have any value at location 2.
A developer faces an ArrayIndexOutofBound exception an array is accessed with an invalid or out of range index value. The provided index value could be either less than 0 or exceed the length of the declared array.
See this example demonstrating ArrayIndexOutofBound exception:
01. class ArrayIndexOutOfBound_Example { 02. public static void main(String args[]) { 03. try { 04. int myArr[] = new int[10]; 05. myArr[14] = 2; // here, an attempt is made to access 14th element in the array 06. //which does not exist as the size of array is 10 07. } catch(ArrayIndexOutOfBoundsException e) { 08. System.out.println ("Invalid index value. The array index is out of bound"); 09. } 10. } 11. }
Invalid index value. The array index is out of bound
This particular exception seems to be encountered rarely but on the contrary, it is common as it mostly happens when dealing with multiple arrays of different sizes and slight miscalculation in the traversing loop can result in an array out of bound error.
Whenever an invalid or incorrect argument is passed to a method, it will result in an illegal argument Exception. For example, if a method is defined with an integer value as one of its parameters, providing a string value as a parameter will throw the IllegalArgumentException. It indicates to the developer that you cannot pass this type of argument to the method.
Consider the following demonstration for this type of exception:
01. import java.io.File; 02. public class IllegalArgumentException_Example { 03. public static String verifyStudentDetails(String name, String ID) { 04. if (name == null) 05. throw new IllegalArgumentException("You cannot leave the name section empty"); 06. 07. if (ID == null) 08. throw new IllegalArgumentException("Please enter your ID"); 09. 10. return verifyID(ID) + verify(name); 11. }
Java allows the conversion of a numeric string into a number. For instance, “12345” can be converted into an integer value, 12345 But if such a string is passed to a method that cannot be converted to a number, the number Format Exception will be thrown.
See the following code snippet:
01. class NumberFormat_Example { 02. public static void main(String args[]) { 03. try { 04. // "twenty-five" is not a valid number. 05. int number = Integer.parseInt ("twenty-five") ; 06. System.out.println(number); 07. } catch(NumberFormatException e) { 08. System.out.println("Invalid format. Number Format Exception is detected"); 09. } 10. } 11. }
Invalid format. Number Format Exception is detected
This code will generate the NumberFormatException as twenty-5 is in invalid format.
ArithmeticException is faced whenever an incorrect arithmetic operation is performed. The most common example is dividing any number by zero, it will throw the arithmetic exception.
01. class ArithmeticException_Example { 02. public static void main(String args[]) { 03. try { 04. int num1 = 100, num2 = 0, ans = 0; 05. int ans = num1/num2; 06. System.out.println (num1 + " / " + num2 + " = " + ans); 07. } catch(ArithmeticException e) { 08. System.out.println ("Invalid operation! divided by 0 error."); 09. } 10. } 11. }
This code will output “Invalid operation! divided by 0 error.”.
We covered all the different types of exceptions in Java with examples. This information of different exceptions is essential for any programmer as exceptions are inevitable and you need to have adequate knowledge for proper handling of them. You can try out these examples yourself to understand more about the nature of these exceptions.
Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use