×

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular logic of the instructions and abruptly ends the process.

Luckily, with a little planning and coding, you can frequently handle these exceptions graciously, enabling your code to keep operating and giving you information for identifying the reason for the unexpected outcome.

How the exceptions are handed

A class or function that encounters an exception generates the exception object and passes the data to that same runtime system (JVM).

The call stack is then traversed by the runtime system to ascertain which layer can manage an exception that was raised or thrown. The search starts with the method where exception was created and proceeds step-by-step through all the call stacks until an exception handler is located. It detects a match when the exception's type matches one that the exception handler can handle.

List of java exceptions with examples

Java defines exception kinds that are connected to its different class libraries. Java also gives users the option to create custom exceptions.

Java exception list

The Built-in Exceptions:

The built-in exceptions are the exceptions that exist in Java libraries. These exceptions can be used to explain a few different fault scenarios. The list of significant built-in Java exceptions is shown below.

  1. ArithmeticException: It is thrown whenever an exceptional circumstance occurs during an arithmetic operation.
  2. ArrayIndexOutOfBoundsException: It must be thrown to let the user know that an array was accessed using an improper index. Its index is either greater or equal to the array size, or it is negative.
  3. ClassNotFoundException: The classNotFoundException in Java arises when the JVM (Java Virtual Machine) tries to load a specific class but can't find the desired class in the classpath you gave, as the name implies. Your classpath is broken as a result of this (which is be a very common problem in the Java world). Beginners in Java may find this issue particularly perplexing. It must be caught or thrown to the caller because ClassNotFoundException is indeed a checked exception.
  4. FileNotFoundException: The java.io package also contains the exception class known as FileNotFoundException. The problem arises when we attempt to access a file that isn't installed on the system. It arises at run time rather than compile time, making it a checked exception.
  5. IOException: When performing input or output actions, such as reading a file or accessing a file, an IOException, or input-output exception, may arise. For instance, if we attempt to read a file using the incorrect path, we receive a FileNotFound Exception. Under the heading of the checked Exceptions, the IOExceptions fall. Exceptions that occur during the compilation of a Java programme are those that have been checked. FileNotFoundException, SSLException, and other subclasses of IOException are only a few examples.
  6. InterruptedException: The execution of any thread that is dozing off or waiting for anything can be interrupted by calling the interrupt() method, which displays an InterruptedException message. The interrupt() function of the Thread class can be used to stop a thread that would be dozing off or waiting.
  7. NoSuchFieldException: When the requested field (or variable) is missing from a class, it is thrown.
  8. NoSuchMethodException: When attempting to access a method that cannot be found, it is thrown.
  9. NullPointerException: Referencing the elements of a null objects causes an exception to be triggered. Null is a symbol for nothing.
  10. NumberFormatException: When a method tries to convert a string to a numeric representation but fails, this exception is thrown.
  11. RuntimeException: This shows an exception that happens in real time.
  12. StringIndexOutOfBoundsException: It is thrown by methods of the String class when such a value seems to be either negative or larger than the length of the string.
  13. IllegalArgumentException: When the method cannot be reached by the programme for a specific operation, an exception that would produce an error or error message. The unchecked exception applies to it.

Illustrations of the Built-in Exception

  • Arithmetic exception
// The ArithmeticException in Java application
class ArithmeticException _Sahithi 
{
    public static void main(String args[])
    {
        try {
            int s = 40, h = 0;
            int r = s/h;  // it cannot be divide by the zero
            System.out.println ("Answer = " + r);
        }
        catch(ArithmeticException e) {
            System.out.println (" it is a number tha cannot be divided by 0 ");
        }
    }
}

Output:

Java exception list
  • NullPointer Exception
// NullPointerException example programme in Java 
class NullPointer_Sahithi
{
    public static void main(String args[])
    {
        try {
            String  h= null; //the value that is null
            System.out.println(h.charAt(0));
        } catch(NullPointerException e) {
            System.out.println("NullPointerException");
        }
    }
}

OUTPUT:

Java exception list
  • StringIndexOutOfBound Exception
// An example StringIndexOutOfBoundsException Java programme
class StringIndexOutOfBound_Sahithi
{
    public static void main(String args[])
    {
        try {
            String h = "The way she is smiling is very attractive "; // length is 42
            char s = h.charAt(44); // here we are accessing the 45th element
            System.out.println(s);
        }
        catch(StringIndexOutOfBoundsException e) {
            System.out.println("…StringIndexOutOfBoundsException…");
        }
    }
}

Output :

Java exception list
  • FileNotFound Exception
// Java example programme for the FileNotFoundException exception
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
 class Sahithi {
 
    public static void main(String args[])  {
        try {
 
            // the file which is in the following does not exist
            File file = new File("E://file.txt");
 
            FileReader sr = new FileReader(file);
        } catch (FileNotFoundException e) {
           System.out.println("No such file exists");
        }
    }
}

Output:

Java exception list
  • IllegalArgumentException: The eligibility of a person to vote is determined by this programme. There won't be any errors thrown if the age is above or equal to 18. An error with an error statement will be generated if the aged is less than 18.

Additionally, "throw new IllegalArgumentException()" can be specified without an error message. In the IllegalArgumentException() function, we may optionally specify Integer.toString(variable name), which will print the name of the argument that does not meet the specified criterion.

/*whatever may be the package// exclude the package name from this text */
 
import java.io.*;
 
class Sahithi {
   public static void print(int a)
    {
         if(s>=18){
          System.out.println("Voting Rights Eligible");
          }
          else{
    
          throw new IllegalArgumentException("Unqualified to Vote");                        
          }
    }
    public static void main(String[] args) {
         Kamal.print(15);
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Unqualified to Vote at Kamal.print(File.java:14)
at Kamal.main(File.java:20)

The user defined exceptions

Java's built-in exceptions may occasionally be unable to adequately explain a particular circumstance. In certain circumstances, the user may also produce what are known as "user-defined Exceptions."

The steps for creating a user-defined exception are as follows.

  • An exception class that is a subclasses of an Exception that class should be created by the user. Given that every exception is a subclass of an Exception that subclass, the user should do the same for his class. This is accomplished as follows:
class OwnException extends Exception
  • It is possible to create a default constructor for the exception class.
OwnException(){}
  • Another option is to create a constructor with parameters that takes a string.

This can be used to store exception information. We can use this to call the superclass(Exception) constructor and pass the string along.

OwnException(String sr)
{
   super(sr);
}
  • It is necessary to generate an object that belongs to the user-defined exception class and toss it through the throw clause in order to invoke an exception of that type, as in:
OwnException sr = new OwnException(“details of the exception”);
throw sr;
  • How to construct your own exception class, MyException, as demonstrated in the application below.
  • Three arrays are used to store information about account numbers, client names, and balance amounts.
  • A for-loop is used in the main() method to display the details. At this point, it is checked to see if the balance in any account falls below the required minimum balance.
  • If this is the case, then "Balance amount is less" is displayed and MyException is raised.

Let us have a look at to the following example

// Programming in Java to display a user-defined exception
 
// When balance is violated, this software throws an exception.
// the below given amount is Rs 20000
class OwnException extends Exception
{
    //account information is stored
    private static int acc[] = {2002, 2003, 2004, 2005};
 
    private static String iden[] =
                 {"Hymavathi", "Janardhan", "Swetha", "Archana", "Sahithi"};
 
    private static double mon[] =
         {20000.00, 22000.00, 3600.0, 899.00, 4100.55};
 
    // it is the default constructor
    OwnException() {    }
 
    // it is the parameterized constructor
    OwnException(String sr) { super(sr); }
 
    // the main() is written here
    public static void main(String[] args)
    {
        try  {
            // display the table's heading
            System.out.println("ACC" + "\t" + "CUST" +
                                           "\t" + "MON");
 
            // show the exact account details
            for (int k = 0; k < 5 ; k++)
            {
                System.out.println(acc[k] + "\t" + iden[k] +
                                               "\t" + mon[k]);
 
                // show your own exception in case of balance < 20000
                if (mon[k] < 20000)
                {
                    OwnException sh =
                       New OwnException("Balance falls short of 20000");
                    throw sh;
                }
            }
        } //it is the end of try
 
        catch (OwnException e) {
            e.printStackTrace();
        }
    }
}

Here the runtime error is

OwnException: Balance falls short of 20000

at OwnException.main(fileProperty.java:36)

Output:

ACC    CUST    MON
2002    Hymavathi    20000.0
2003    Janardhan    22000.0
2004    Swetha    3600.0
2005    Archana    899.0

Related Topics

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.