6

Exception Hierarchy in Java

 1 year ago
source link: https://www.thejavaprogrammer.com/exception-hierarchy-in-java/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Exception Hierarchy in Java

Whenever any unexpected event like if required Index is more than the array size happens, it results in the stopping of the program. The name of this condition is an “Exception”.

There are many types of exceptions occurred in java, and there is a certain hierarchy followed by java. We will be exploring this hierarchy through this blog.

“Throwable class” is the topmost class in the hierarchy. It is mainly divided into 2 types which are Exception class and Error class.

Exception Hierarchy in Java

Image Source

Errors

Errors are problems that are happening due to failures in the system or Java virtual machine (JVM). One common example of an error can be a system crash. Errors can only occur when we are running a program (runtime), this is the reason error is an unchecked type.

Here is an example of an Error:

package myproject;
import java.util.*;
public class errorexample {
public static void print(String mystr) {
print(mystr);
public static void main(String[] args) {
     errorexample.print("This is my string");

Output:

Exception in thread "main" java.lang.StackOverflowError
at myproject.errorexample.print(errorexample.java:5)

Explanation:

In the above code, we can see that the print function is calling itself again and again, there is no ending for this function call. This results in the filling of the Stack and we get the “StackOverflowError”. It cannot be solved directly with the use of debugging.

Exceptions

Exceptions are errors happening due to problems in the code/program. It can occur at either runtime (unchecked exception) or compile time (checked exception). The checked exception are needed to be corrected through the program although unchecked exceptions need not be solved precisely.

Here is an example of an Exception:

package myproject;
import java.util.*;
public class exceptionexample {
public static void main(String[] args) {
      Scanner sc=new Scanner(System.in);
  System.out.println("Enter first number:");
      int first= sc.nextInt();
      System.out.println("Enter second number:");
      int second=sc.nextInt();
      int result_div=first/second;
      //Since dividing any number by 0 will result into an infinite number so we will give 0 as second number
      System.out.println(result_div);

Output:

Enter first number:
Enter second number:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at myproject.exceptionexample.main(exceptionexample.java:11)

Explanation:

In the above code, we are dividing any particular numeric value with 0. This is not possible as it will result in an infinite number. As division is an Arithmetic Operation and it cannot be performed in this case therefore the “ArithmeticException” occurs.

Custom Exceptions

“Custom” word states that the complete functionality of any application is designed by the person. So custom exceptions are created by the coder according to the need of the program. Therefore it is also known as user defined exceptions. This is one of the advantages that java includes, i.e, giving the choice to programmers to create their exceptions.

import java.io.*;
class invalidgender extends Exception{
public invalidgender(String str) {
super(str);
public class customexception {
public static void main(String[] args) throws invalidgender {
String gender="maele";
if(gender=="male" || gender=="female") {
System.out.println("The gender you have entered is "+gender);
}else {
throw new invalidgender("You have entered the wrong gender");

Output:

Exception in thread "main" invalidgender: You have entered the wrong gender
at customexception.main(customexception.java:15)

Explanation:

In the starting, we are creating a child class of Exception class naming it as invalidgender class. Now we will create a constructor of the invalidgender class, and call the constructor of the Exception class using super keyword.

While declaring the main function we will write throws invalidgender, throws keyword will help the program to get the information about the invalidgender exception.

If-else condition is used to find whether the written gender is either male or female. If it is either male or female we will go inside the if-condition and print the entered the gender. Otherwise we are going to call the invalidgender exception.

The argument passed as an string inside the invalidgender exception will be printed.

There are two types of predefined exceptions in java:

1. Checked Exceptions

Exceptions which are having the probability to arise while compiling are known as checked exceptions. These type of exceptions are needed to be handled specifically and can’t be ignored. You can handle checked exceptions using try-catch block.

For Example: If the user is trying to access a file which is not even created yet, then the program will return a File Not Found Exception.

import java.io.*;
public class checkedexception {
public static void main(String[] args) {
File myfile = new File("/home/thejavaprogrammer/file.txt");
    FileReader fileReaded = new FileReader(myfile);
    System.out.println("Successful");

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at checkedexception.main(checkedexception.java:8)

Handled Checked Exception

import java.io.*;
public class checkedexception {
public static void main(String[] args) throws IOException {
File myfile = new File("/home/thejavaprogrammer/file.txt");
    FileReader fileReaded = new FileReader(myfile);
    System.out.println("Successful");

Output:

Successful

Some more examples of Checked Exceptions:

1. Illegal Access Exception: This exception is thrown whenever any application tries to change or get any field but the method is not allowed to access that particular field.

2. Class Not Found Exception: This exception is thrown when the file tries to load the class directly using its fully qualified name and is not able to find its defination.

3. No Such Field Exception: This exception is thrown whenever there is an undeclared variable which is used in program.

2. Unchecked Exceptions

Exception which mostly occurs when the program is running, then it is known as an unchecked exception. The compiler doesn’t checks this code so it directly goes into runtime therefore they are also known as runtime exceptions. The bugs in the code are the reason for this exception.

If someone tries to access an index of one list which is not available then it is known as ArrayIndexOutOfBounds.

import java.io.*;
public class uncheckedexception {
public static void main(String[] args) {
int arr[]= {1,2,3,4};
System.out.println(arr[4]);

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at uncheckedexception.main(uncheckedexception.java:8)

So in the above case, we cannot access the elements having an index beyond 3.

Some more examples of Unchecked Exceptions:

1. Arithmetic Exception: This exception is thrown whenever any problems in arithmetic occurs, for example if we try to divide any number by 0.

2. Null Pointer Exception: This exception is thrown by Java Virtual Machine (JVM) whenever we try to use null rather than an object.

3. Array Store Exception: This exception is thrown when we try to insert value of different datatype that the array can hold.

Conclusion

Exceptional hierarchy plays a major role in making a better application. By now you must have understood different layers of exceptions in java. If you are having any doubts feel free to write them in the comments and we will try our best to solve them.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK