

{"id":12497,"date":"2018-04-06T09:15:01","date_gmt":"2018-04-06T09:15:01","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=12497"},"modified":"2026-05-20T10:15:21","modified_gmt":"2026-05-20T04:45:21","slug":"java-exception","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-exception\/","title":{"rendered":"Java Exception &#8211; Explore Checked &amp; Unchecked Exception With Examples"},"content":{"rendered":"<p>In Java, a programmer might encounter difficulties or unusual scenarios while writing a program. It can be a problem with the program syntax, or it can be difficulties in getting the desired output. Whatever the case may be, it is important to resolve these issues to ensure the program produces a favourable output. In this article, we will take a look at these unusual scenarios and how to handle them in the program. We will learn about Java exceptions and their types.<\/p>\n<h3>What are Exceptions in Java?<\/h3>\n<p>We know exceptions are abnormal conditions, which are not a part of our day-to-day life. In Java programming, exceptions are events that hamper the regular flow of a program. It is a kind of object that is thrown during runtime.<\/p>\n<h3>Cause of Exception in Java<\/h3>\n<p><strong>An exception can occur due to various reasons. Some common causes of exceptions are:<\/strong><\/p>\n<ul>\n<li>by the user during an input operation.<\/li>\n<li>In syntax by the programmer.<\/li>\n<li>Due to a lack of resources, such as insufficient memory.<\/li>\n<\/ul>\n<h3>Categories of exceptions in Java<\/h3>\n<p><strong>In Java, there are two categories of exceptions:<\/strong><\/p>\n<p><strong>1. JVM exceptions:<\/strong> These are exceptions and errors that are thrown by the JVM only. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.<\/p>\n<p><strong>2. Programmatic Exceptions:<\/strong> These are exceptions that the application or the API programmers throw explicitly. Examples: IllegalArgumentException, IllegalStateException.<\/p>\n<h3>Hierarchy of Java Exceptions<\/h3>\n<p>In Java, the exceptions are present in the java.lang.Throwable class. Inheriting the class are two subclasses, Exception and Error, which are further inherited by other subclasses. The hierarchy of the Throwable class is:<\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/hierarchy-of-java-exceptions.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-109007\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/hierarchy-of-java-exceptions.webp\" alt=\"hierarchy of java exceptions\" width=\"1440\" height=\"691\" \/><\/a><\/p>\n<h3>Types of Java Exceptions<\/h3>\n<p>There are mainly two types of exceptions, Checked and Unchecked Exceptions, but according to Oracle, there are actually three types of exceptions:<\/p>\n<p><strong>1. Checked Exception<\/strong><br \/>\n<strong>2. Unchecked Exception<\/strong><br \/>\n<strong>3. Error<\/strong><\/p>\n<p>An error is also a type of unchecked exception.<\/p>\n<h3>Difference Between Java Checked Exceptions, Unchecked Exceptions, and Errors<\/h3>\n<p><strong>1. Checked Exception in Java:<\/strong> The exception classes that directly inherit from the Throwable class, except RuntimeException and Error, are checked exceptions. They are checked during compilation time. For example: IOException, SQLException, ClassNotFoundException, etc.<\/p>\n<p><strong>2. Unchecked Exception in Java:<\/strong> The exception classes inheriting the RuntimeException class are unchecked exceptions. They are not checked at compilation time but during runtime. For example: ArithmeticException, IndexOutOfBoundsException, etc.<\/p>\n<p><strong>3. Error in Java:<\/strong> The exceptions that are irrecoverable are known as errors. They are also checked at runtime. For Example: OutOfMemoryError, VirtualMachineError, etc.<\/p>\n<h3>How JVM Handles an Exception(Default Exception Handling)<\/h3>\n<p>If an exception is encountered inside the method, it creates an object called the Exception Object. The object is then transferred to the run-time system or JVM. The object contains all the information of the exception, starting from the name and description of the exception, and the current state of the exception. Various methods might be called where the exception occurred; the ordered list of these methods is known as the call stack.<\/p>\n<p><strong>After this, the following will happen:<\/strong><\/p>\n<ul>\n<li>The JVM searches the call stack to look for the method that contains the code to handle the occurred exception. This block of code is known as an Exception handler.<\/li>\n<li>Now the JVM looks for the method where the exception took place.<\/li>\n<li>If the JVM finds an appropriate handler, it passes the exception method to the handler.<\/li>\n<li>If the JVM is unable to find an appropriate handler, it sends the object to the default exception handler, which prints a default message and terminates the abnormality.<\/li>\n<\/ul>\n<p><strong>Code to explain Exception handling by JVM<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\npublic class exception\r\n{\r\n    public static void main(String args[]){\r\n          \r\n        String str = null;\r\n        System.out.println(str.length());\r\n          \r\n    }\r\n}\r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">java.lang.NullPointerException<br \/>\nat com.DataFlair.exceptions.exception.main(exception.java:7)<br \/>\nat com.DataFlair.exceptions.__SHELL0.run(__SHELL0.java:6)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br \/>\nat java.base\/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)<br \/>\nat java.base\/java.lang.reflect.Method.invoke(Method.java:566)<br \/>\nat bluej.runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)<br \/>\nat bluej.runtime.ExecServer.runOnTargetThread(ExecServer.java:964)<br \/>\nat bluej.runtime.ExecServer$3.run(ExecServer.java:846)<\/div>\n<h3>How a programmer handles an exception(Customized Exception Handling):<\/h3>\n<p>Programmers can handle exceptions using the five keywords: try, catch, throw, throws, and finally. The code that may contain exceptions is passed through the try block, which tries the code for exceptions; the exception is then thrown to the catch block, which handles the exception. After that, the finally block is used, which runs whatever. The throws and throw keywords are used to give a customized exception.<\/p>\n<p>The proper use of try-catch and finally block is given below in this article.<\/p>\n<h3>The common exception scenarios in Java<\/h3>\n<p><strong>1. SQLException:<\/strong> Using invalid SQL queries in the Java program might lead to this kind of exception.<\/p>\n<p><strong>2. IOException:<\/strong> Whenever the JVM fails to open the IO stream, this exception is thrown by the JVM.<\/p>\n<p><strong>3. ClassNotFoundException:<\/strong> If we try to access a class that does not exist or has been deleted from the path, the JVM throws this error.<\/p>\n<p><strong>4. ArithmeticException:<\/strong> Dividing a number by zero will give an ArithmeticException, as we all know, anything divided by zero is infinite.<\/p>\n<p><strong>Code to illustrate ArithmeticException in Java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\npublic class exception\r\n{\r\n     public static void main(String args[])\r\n  {\r\n    int exp = 50\/0;\r\n    System.out.println(\"This is an Arithmetic Exception: \" + exp);\r\n  }\r\n}\r\n<\/pre>\n<p><strong>The output of the above Code:<\/strong><\/p>\n<div class=\"code-output\">java.lang.ArithmeticException: \/ by zero<br \/>\nat com.DataFlair.exceptions.exception.main(exception.java:6)<br \/>\nat com.DataFlair.exceptions.__SHELL0.run(__SHELL0.java:6)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br \/>\nat java.base\/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)<br \/>\nat java.base\/java.lang.reflect.Method.invoke(Method.java:566)<br \/>\nat bluej.runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)<br \/>\nat bluej.runtime.ExecServer.runOnTargetThread(ExecServer.java:964)<br \/>\nat bluej.runtime.ExecServer$3.run(ExecServer.java:846)<\/div>\n<p><strong>5. NullPointerException:<\/strong> Trying to find the length of a null string is an example of this kind of exception. We all know that null doesn\u2019t have a physical memory assigned to it, thus it doesn\u2019t have a length. So, it will give a NullPointerException.<\/p>\n<p><strong>Code to explain NullPointerException in Java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\npublic class exception\r\n{\r\n     public static void main(String args[])\r\n    {\r\n        String str= null;\r\n        System.out.println(str.length());\r\n     }\r\n}\r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">java.lang.NullPointerException<br \/>\nat com.DataFlair.exceptions.exception.main(exception.java:7)<br \/>\nat com.DataFlair.exceptions.__SHELL1.run(__SHELL1.java:6)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br \/>\nat java.base\/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)<br \/>\nat java.base\/java.lang.reflect.Method.invoke(Method.java:566)<br \/>\nat bluej.runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)<br \/>\nat bluej.runtime.ExecServer.runOnTargetThread(ExecServer.java:964)<br \/>\nat bluej.runtime.ExecServer$3.run(ExecServer.java:846)<\/div>\n<p><strong>6. NumberFormatException:<\/strong> If we declare a variable as a string with multiple characters and try to convert it into a digit, it will give a NumberFormatException.<\/p>\n<p><strong>Code to Explain NumberFormatException in Java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\npublic class exception\r\n{\r\n     public static void main(String args[])\r\n    {\r\n        String str= \"DataFlair\";\r\n        int num=Integer.parseInt(str);\r\n        System.out.println(num);\r\n     }\r\n}\r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">java.lang.NumberFormatException: For input string: &#8220;DataFlair&#8221;<br \/>\nat java.base\/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)<br \/>\nat java.base\/java.lang.Integer.parseInt(Integer.java:652)<br \/>\nat java.base\/java.lang.Integer.parseInt(Integer.java:770)<br \/>\nat com.DataFlair.exceptions.exception.main(exception.java:7)<br \/>\nat com.DataFlair.exceptions.__SHELL2.run(__SHELL2.java:6)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br \/>\nat java.base\/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)<br \/>\nat java.base\/java.lang.reflect.Method.invoke(Method.java:566)<br \/>\nat bluej.runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)<br \/>\nat bluej.runtime.ExecServer.runOnTargetThread(ExecServer.java:964)<br \/>\nat bluej.runtime.ExecServer$3.run(ExecServer.java:846)<\/div>\n<p><strong>7. ArrayIndexOutOfBoundException:<\/strong> This is the most common exception that occurs in a program. Programmers often forget the size of the array and call for an index that is larger than the size of the array, causing an ArrayIndexOutOfBoundException.<\/p>\n<p><strong>Code to Explain ArrayIndexOutOfBOundException in Java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\npublic class exception\r\n{\r\n     public static void main(String args[])\r\n    {\r\n        int num[]=new int[50];\r\n        num[100]=1000;\r\n        System.out.println(num[100]);\r\n     }\r\n}\r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 50<br \/>\nat com.DataFlair.exceptions.exception.main(exception.java:7)<br \/>\nat com.DataFlair.exceptions.__SHELL3.run(__SHELL3.java:6)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br \/>\nat java.base\/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)<br \/>\nat java.base\/java.lang.reflect.Method.invoke(Method.java:566)<br \/>\nat bluej.runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)<br \/>\nat bluej.runtime.ExecServer.runOnTargetThread(ExecServer.java:964)<br \/>\nat bluej.runtime.ExecServer$3.run(ExecServer.java:846)<\/div>\n<p><strong>8. IllegalArgumentException:<\/strong> IllegalArgumentException is thrown when we pass an incorrect argument into a method.<\/p>\n<p><strong>Code to explain Java IllegalArgumentException:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\npublic class exception\r\n{\r\n     public static void main(String[] args)\r\n    {\r\n        Thread t1 = new Thread(new Runnable() {\r\n            public void run()\r\n            {\r\n                try {\r\n                    Thread.sleep(-10);\r\n                }\r\n                catch (InterruptedException e) {\r\n                    e.printStackTrace();\r\n                }\r\n                System.out.println(\"DataFlair\");\r\n            }\r\n        });\r\n        t1.setName(\"Test Thread\");\r\n        t1.start();\r\n    }\r\n}\r\n\r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">Exception in thread &#8220;Test Thread&#8221; java.lang.IllegalArgumentException: timeout value is negative<br \/>\nat java.base\/java.lang.Thread.sleep(Native Method)<br \/>\nat com.DataFlair.exceptions.exception$1.run(exception.java:10)<br \/>\nat java.base\/java.lang.Thread.run(Thread.java:834)<\/div>\n<p><strong>9. IllegalStateException:<\/strong> If we call a method at the wrong time, we get the IllegalStateException. It means that the state of the environment does not meet the requirements of the operation.<\/p>\n<p><strong>Code to understand Java IllegalStateException<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\nimport java.util.ArrayList;\r\nimport java.util.ListIterator;\r\npublic class exception\r\n{\r\n     public static void main(String args[]) {\r\n      ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();\r\n      list.add(\"Data\");\r\n      list.add(\"Flair\");\r\n      ListIterator&lt;String&gt; it = list.listIterator();\r\n    it.remove();\/\/Removing element without moving the first position.\r\n   }\r\n}\r\n\r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">java.lang.IllegalStateException<br \/>\nat java.base\/java.util.ArrayList$Itr.remove(ArrayList.java:1009)<br \/>\nat com.DataFlair.exceptions.exception.main(exception.java:11)<br \/>\nat com.DataFlair.exceptions.__SHELL0.run(__SHELL0.java:6)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br \/>\nat java.base\/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)<br \/>\nat java.base\/java.lang.reflect.Method.invoke(Method.java:566)<br \/>\nat bluej.runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)<br \/>\nat bluej.runtime.ExecServer.runOnTargetThread(ExecServer.java:964)<br \/>\nat bluej.runtime.ExecServer$3.run(ExecServer.java:846)<\/div>\n<h3>Exception Handling in Java<\/h3>\n<p>In Java, exceptions can be handled inside the program itself using exception handling. Exception handling can be used to handle runtime exceptions such as IOExceptions, ArithmeticExceptions, etc.<\/p>\n<h3>Advantages of using Java Exception Handling<\/h3>\n<ul>\n<li>Using exception handling, we can maintain the regular flow of the program. We have seen earlier that exceptions disrupt the regular flow of a program. Thus, exception handling skips the exception without hampering the flow of the program.<\/li>\n<li><strong>Retaining the Program:<\/strong> Exception handling is a process of retaining the execution of a program by suggesting a solution to the exceptions that arise. It optimises the code by making a way to run the program.<\/li>\n<\/ul>\n<h3>Important Keywords Related to Java Exception Handling<\/h3>\n<p><strong>1. try:<\/strong> The try block is the block where the block of code that needs to be checked for exceptions is placed. The try block is followed by a catch or finally block; it cannot stand alone.<\/p>\n<p><strong>2. catch:<\/strong> Using the catch block, we can catch the exception thrown by the try block. It is declared after the try block.<\/p>\n<p><strong>3. finally:<\/strong> Using the finally block, we can execute an important piece of code because the finally block will be executed regardless of what the outcome is from the try block.<\/p>\n<p><strong>4. throw:<\/strong> Using the throw keyword, we can throw a predefined exception.<\/p>\n<p><strong>5. throws:<\/strong> Using the throws keyword, we can declare a new exception from the exception classes.<\/p>\n<h3>Java Exception Methods<\/h3>\n<table>\n<tbody>\n<tr>\n<td><b>SL. No.<\/b><\/td>\n<td><b>Method\u00a0<\/b><\/td>\n<td><b>Description\u00a0<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">1<\/span><\/td>\n<td><span style=\"font-weight: 400\">public String getMessage()<\/span><\/td>\n<td><span style=\"font-weight: 400\">This method returns a string message explaining the exception that occurred.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">2<\/span><\/td>\n<td><span style=\"font-weight: 400\">public Throwable getCause()<\/span><\/td>\n<td><span style=\"font-weight: 400\">This method throws the cause of the occurred exception.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">3<\/span><\/td>\n<td><span style=\"font-weight: 400\">public String toString()<\/span><\/td>\n<td><span style=\"font-weight: 400\">This method returns the message of the getMessage() method along with the class of exception concatenated to it.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">4<\/span><\/td>\n<td><span style=\"font-weight: 400\">public void printStackTrace()<\/span><\/td>\n<td><span style=\"font-weight: 400\">This method returns the output of the toString() method along with its stack trace<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">5<\/span><\/td>\n<td><span style=\"font-weight: 400\">public StackTraceElement [] getStackTrace()<\/span><\/td>\n<td><span style=\"font-weight: 400\">This method returns an array containing all the elements of the stack trace.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Example of a program using exception handling using a try-catch block in Java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\npublic class exceptionhandling\r\n{\r\n  public static void main(String[] args) {\r\n    try {\r\n      char[] ch = {'D', 'A', 'T', 'A', 'F', 'L', 'A', 'I', 'R'};\r\n      System.out.println(ch[10]);\r\n    } catch (Exception e) {\r\n      System.out.println(\"Something went wrong in the indexing of Array\");\r\n    } finally {\r\n      System.out.println(\"The 'try catch' is over, continuing the program from here!\");\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<p><strong>The output of the above Program:<\/strong><\/p>\n<div class=\"code-output\">Something went wrong in the indexing of Array<br \/>\nThe &#8216;try catch&#8217; is over, continuing the program from here!<\/div>\n<h3>The try-with-resources block<\/h3>\n<p>The try-with-resources block is the most recent addition to Java exception handling. As a result, the Java 7 update introduced the try-with-resource block. It automatically closes the resources used within the try-catch block. It is very simple to use; we just have to declare the resources within parentheses, and the resources are automatically closed.<\/p>\n<p><strong>Syntax of try-with-resources block in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">try(FileReader f = new FileReader(\"Path of the resource file\")) {\r\n   \/\/ use the resource\r\n   } catch () {\r\n      \/\/ body of catch \r\n   }\r\n}\r\n\r\n<\/pre>\n<h3>User-defined or customized Exception in Java<\/h3>\n<p>Not all exceptions are defined in the JVM; there are situations where the programmer might have to define an exception of their own. Therefore, defining an exception as per the needs of a user is called a user-defined exception.<\/p>\n<p>Java has the provision to create a customized exception to serve this purpose.<\/p>\n<h3>Rules for creating a Java Exception<\/h3>\n<p><strong>To create a customized Java exception, we have to keep in mind the following points:<\/strong><\/p>\n<ul>\n<li>The user-defined exception class should extend the built-in Exception class.<\/li>\n<li>The user must override the toString() method in the user-defined exception class.<\/li>\n<\/ul>\n<p><strong>Code to create and use a user-defined Exception class in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.exceptions;\r\npublic class UserDefException extends Exception\r\n{\r\n  private static int year;\r\n  public UserDefException(int year)\r\n  {\r\n    this.year=year;\r\n  }\r\n  public String toString()\r\n  {\r\n    return \"Age below 18, Underaged!!!\";\r\n  }\r\n  public static void main(String args[]) throws Exception\r\n  {\r\n    UserDefException obj = new UserDefException( 2005 );\r\n    if(year &gt; 2003)\r\n    {\r\n      throw new UserDefException(year);\r\n    }\r\n    else\r\n    {\r\n      System.out.println(\"Entered year is: \" +year);\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">Age below 18, Underaged!!!<br \/>\nat com.DataFlair.exceptions.UserDefException.main(UserDefException.java:18)<br \/>\nat com.DataFlair.exceptions.__SHELL0.run(__SHELL0.java:6)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br \/>\nat java.base\/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br \/>\nat java.base\/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)<br \/>\nat java.base\/java.lang.reflect.Method.invoke(Method.java:566)<br \/>\nat bluej.runtime.ExecServer$3.lambda$run$0(ExecServer.java:849)<br \/>\nat bluej.runtime.ExecServer.runOnTargetThread(ExecServer.java:964)<br \/>\nat bluej.runtime.ExecServer$3.run(ExecServer.java:846)<\/div>\n<p>So, we can see that the program gives an exception that was created by us and not an in-built exception. Therefore, this can be very useful to check user input for certain criteria.<\/p>\n<h3>Advanced Exception Handling Techniques in Java<\/h3>\n<p>Java exception handling offers a robust mechanism for managing errors during program execution. However, for complex applications, you might explore more advanced techniques to enhance code readability, maintainability, and error handling practices. Here are some noteworthy approaches:<\/p>\n<p><strong>1. Nested try-catch blocks:<\/strong> Nested try-catch blocks allow you to create a layered exception handling structure. An inner try block can potentially throw an exception that&#8217;s caught by an outer catch block. Hence, this enables you to handle specific exceptions at different levels within your code.<\/p>\n<p><strong>2. Chained exceptions:<\/strong> Chained exceptions provide a way to link exceptions together, forming a cause-and-effect chain. By throwing a new exception that encapsulates the original exception as its cause, you can create a more informative exception hierarchy. Therefore, this can be helpful for debugging purposes, as it allows you to trace the root cause of an exception more easily.<\/p>\n<p><strong>3. Custom exceptions:<\/strong> As discussed earlier, Java allows you to create custom exceptions for specific error scenarios in your application. However, when designing custom exceptions, consider extending the appropriate built-in exception class (like RuntimeException or Exception) and providing informative error messages within your custom exception class.<\/p>\n<h3>Important Points to Remember:<\/h3>\n<ul>\n<li>In a function, more than one statement can throw an exception. A separate try-catch block for each statement is necessary.<\/li>\n<li>Each exception is handled by an exception handler. To associate an exception handler with an exception, we need a catch block.<\/li>\n<li>A try block can have 0 to n number of catch blocks, but it cannot have more than one finally block.<\/li>\n<li>A finally block in Java is optional; it runs regardless of the output of the try block.<\/li>\n<li>A try block must have either a catch or a finally block.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>In this article, we saw the different exceptions present in Java and where they are present. Therefore, we also saw how to handle these exceptions properly to make the program execute smoothly.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Java, a programmer might encounter difficulties or unusual scenarios while writing a program. It can be a problem with the program syntax, or it can be difficulties in getting the desired output. Whatever&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":108839,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[2494,4435,4436,7414,7483,7484,8938],"class_list":["post-12497","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-checked-exceptions-in-java","tag-exception-hierarchy-in-java","tag-exception-in-java","tag-java-catch-exception","tag-java-error","tag-java-exception","tag-multiple-catch-blocks-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Exception - Explore Checked &amp; Unchecked Exception With Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"When a program terminates unexpectedly that condition is called Java Exception. Learn types of java exception- checked, unchecked &amp; error.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/java-exception\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Exception - Explore Checked &amp; Unchecked Exception With Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"When a program terminates unexpectedly that condition is called Java Exception. Learn types of java exception- checked, unchecked &amp; error.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-exception\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-04-06T09:15:01+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-20T04:45:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/exceptions-in-java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Exception - Explore Checked &amp; Unchecked Exception With Examples - DataFlair","description":"When a program terminates unexpectedly that condition is called Java Exception. Learn types of java exception- checked, unchecked & error.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/java-exception\/","og_locale":"en_US","og_type":"article","og_title":"Java Exception - Explore Checked &amp; Unchecked Exception With Examples - DataFlair","og_description":"When a program terminates unexpectedly that condition is called Java Exception. Learn types of java exception- checked, unchecked & error.","og_url":"https:\/\/data-flair.training\/blogs\/java-exception\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-04-06T09:15:01+00:00","article_modified_time":"2026-05-20T04:45:21+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/exceptions-in-java.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/java-exception\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-exception\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Java Exception &#8211; Explore Checked &amp; Unchecked Exception With Examples","datePublished":"2018-04-06T09:15:01+00:00","dateModified":"2026-05-20T04:45:21+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-exception\/"},"wordCount":2520,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-exception\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/exceptions-in-java.jpg","keywords":["Checked exceptions in java","Exception Hierarchy in Java","Exception in Java","Java Catch Exception","Java Error","Java Exception","Multiple Catch Blocks in Java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-exception\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-exception\/","url":"https:\/\/data-flair.training\/blogs\/java-exception\/","name":"Java Exception - Explore Checked &amp; Unchecked Exception With Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-exception\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-exception\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/exceptions-in-java.jpg","datePublished":"2018-04-06T09:15:01+00:00","dateModified":"2026-05-20T04:45:21+00:00","description":"When a program terminates unexpectedly that condition is called Java Exception. Learn types of java exception- checked, unchecked & error.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-exception\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-exception\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-exception\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/exceptions-in-java.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/exceptions-in-java.jpg","width":1200,"height":628,"caption":"exceptions in java"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-exception\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Java Exception &#8211; Explore Checked &amp; Unchecked Exception With Examples"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/12497","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=12497"}],"version-history":[{"count":20,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/12497\/revisions"}],"predecessor-version":[{"id":148381,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/12497\/revisions\/148381"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/108839"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=12497"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=12497"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=12497"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}