Home » Java Basics » exceptions » Java throw Exception Example

About Abhinav Nath Gupta

Abhinav holds a Master degree in Computer Science and Engineering from the National Institute of Technology Karnataka. He has finished his graduation from Information Technology Department in the Anand Engineering College, Agra. During his studies he has been involved with a large number of projects ranging from Networking and Cryptography. He works as a software development engineer at a software development firm in bengaluru where he is mainly involved with projects based on Nodejs. He is interested in cryptography, data security, cryptocurrency and cloud computing, and published articles regarding these topics. He can be reached at abhi.aec89@gmail.com.

Java throw Exception Example

In this post, we feature a comprehensive Java throw Exception Example. 

1. What is an Exception in Java?

Exception is mechanism which Java uses to handle any unforeseen use-case/scenario. Basically an exception is thrown when either something unexpected happened during code execution which is not covered in any code block(converting some null value to lowercase()) or some IO operation communicating with some third party resource(reading a non existent file).

2. Types Of Exceptions in Java

Exceptions are broadly divided into 2 categories.

2.1 Checked Exception

Checked Exceptions are the exceptions which are notified at the compilation step of the Java program. They are also known as the compile-time exceptions. For these kinds of exceptions, the onus of handling lies on the programmer.

Following code snippet shows the example of the checked exception.

CheckedException.java
public class CheckedException {
    public static void main(String[] args) {
        try {
            int a = 2 / 0;
        } catch (Exception e) {
            System.out.println("Cannot divide a number with zero.");
        }
    }
}

the output of the above code is shown in Fig. 1 below.

Java throw Exception - throw exception java - Output of CheckException
Fig. 1 Output of CheckException.java

2.2 Unchecked Exception

An Unchecked Exception occurs at the runtime of the java code.These are called Runtime Exceptions. For these kinds of exceptions, the onus of handling lies on the programmer.

Following code snippet shows an example of Unchecked Exceptions

UnCheckedException.java
public class UnCheckedException {
   
   public static void main(String args[]) {
      int num[] = {1, 2, 3, 4};
      System.out.println(num[5]);
   }
}

the output of above code is shown in the Fig. 2 below.

Java throw Exception - throw exception java - Output of UnCheckedException
Fig. 2 Output of UnCheckedException.java

Above mentioned error can be handled using the try-catch as shown in code snippet below.

UnCheckedExceptionWithTryCatch.java
public class UnCheckedExceptionWithTryCatch {
    public static void main(String[] args) {
        try{
            int num[] = {1, 2, 3, 4};
            System.out.println(num[5]);
        }catch (Exception e){
            System.out.println("Index out of bound");
        }
    }
}

The output of the above code can be shown in fig. 3 below.

Java throw Exception - throw exception java - UnCheckedExceptionWithTryCatch
Fig. 3 Output of UnCheckedExceptionWithTryCatch.java

3. Exception Hierarchy

Exceptions follow a certain hierarchy while dictates how exceptions are resolved. Following diagram in Fig. 4. show the hierarchy.

Java throw Exception - Exception Hierarchy
Fig. 4 Exception Hierarchy in Java

4. Methods in Exception Class

Following are the most commonly used methods of the Exception class.

  1. public String getMessage()
    Returned the detailed message about what caused the exception that has occurred.
  2. public Throwable getCause()
    Returned the cause of the Exception in the form of Throwable Object.
  3. public String toString()
    Return the name of the class concatenated with the result of the getMessage().
  4. public void printStackTrace()
    Print the output of the Java Error stream, System.err, along with the output of the toString() function.
  5. public StackTraceElement [] getStackTrace()
    Return an array containing containing all the method calls which resulted in error, with element on index 0 represent the last method invoked before error and element on last index represent the method at the bottom of the call stack.
  6. public Throwable fillInStackTrace()
    Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

5. Exception Keywords

There are couple of Java Keywords which are used extensively in Exception Handling.

  1. try:
    try keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone..
  2. catch
    catch code block contains the code sequence which should execute once exception has occurred.
  3. finally
    finally code block contains the code which will execute whether the exception has occurred or not.
  4. throw
    throw keyword is used to explicitly throw an exception from the code flow.
  5. throws
    throws keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

6. Exception Handling with Multiple Catch Blocks

Now we will discuss a code example with the multiple catch blocks. The idea is to handle more than one exceptions for a single try block.

CatchMultipleException.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CatchMultipleException {
    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream("");
            byte x = (byte) file.read();
        } catch (FileNotFoundException f) {
            f.printStackTrace();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}

The output of the above code can be shown in Fig. 5 below.

catchMultipleException
ig. 5 Output of CatchMultipleException.java

In the above code example there were 2 possibilities of the Java exceptions which could be thrown. One is IOException and other is FileNotFoundException. FileNotFoundException is the Specific one and IOException is the generic one, which means that the IOException is parent class of FileNotFoundException. If we put the catch block of IOException above the FileNotFoundException then there will be a compilation failure. Compilation failure will be there because we are catching the Exception of parent class (IOException) before the exception of the child Class (FileNotFoundException).

7. Exception Handling with Custom Exception Class

In this example, we feature a comprehensive Java throw Exception Example. We are going to demonstrate how to catch multiple exceptions, using a try-catch block. To catch multiple exceptions we have followed the steps below:

  • We have created a method, checkPass(String pass) that reads a String password and throws a NoPassException if the password is null and a ShortPassException if the password’s length is shorter that a specific min length.
  • NoPassException class extends the Exception and uses the Exception’s constructors in its constructors. It is the exception thrown for no password.
  • ShortPassException class extends the Exception and also uses the Exception’s constructors in its constructors. It is the exception thrown for short password.
  • We invoke the checkPass(String pass) method in a try-catch block, using the two exceptions in the catch keywords.
  • There is also a finally keyword, whose block will always be executed.

Let’s take a look at the code snippet that follows:

CatchMultipleExceptionWithCustomException.java
public class CatchMultipleExceptionsWithCustomException {
    public static void main(String[] args) {
  // We demonstrate with a short password
  try {
CatchMultipleExceptions.checkPass("pass");
  } catch (NoPassException e) {
e.printStackTrace();
  } catch (ShortPassException e) {
e.printStackTrace();
  } finally {
System.out.println("Finally block is always executed");
  }
  
  // We demonstrate with no password
  try {
CatchMultipleExceptions.checkPass(null);
  } catch (NoPassException e) {
e.printStackTrace();
  } catch (ShortPassException e) {
e.printStackTrace();
  } finally {
System.out.println("Finally block is always executed");
  }
  
  // We demonstrate with valid password
  try {
CatchMultipleExceptions.checkPass("123456");
System.out.println("Password check : OK");
  } catch (NoPassException e) {
e.printStackTrace();
  } catch (ShortPassException e) {
e.printStackTrace();
  } finally {
System.out.println("Finally block is always executed");
  }
    }
    // Our business method that check password validity and throws NoPassException and ShortPassException
    public static void checkPass(String pass) throws NoPassException, ShortPassException {
  int minPassLength = 5;
  if (pass == null)
throw new NoPassException("No pass provided");
  if (pass.length() < minPassLength)
throw new ShortPassException("The password provided is too short");
    }
}
//A custom business exception for no password
class NoPassException extends Exception {
    NoPassException() {
    }
    NoPassException(String message) {
  super(message);
    }
    NoPassException(String message, Throwable cause) {
  super(message, cause);
    }
}
// A custom business exception for short password
class ShortPassException extends Exception {
    ShortPassException() {
    }
    ShortPassException(String message) {
  super(message);
    }
    ShortPassException(String message, Throwable cause) {
  super(message, cause);
    }
}

This was an example of Java throw Exception. Now you know how to catch multiple exceptions, using a try-catch block in Java.

The output of the above code can be shown in Fig. 6 below.

CatchMultipleExceptionsWithCustomException
Fig. 6 Output of CatchMultipleExceptionsWithCustomException.java

8. Best Practices for Exception Handling

Exception handling is quite complex and troubles newbies and seasoned developers alike. But over the years with countless trial and errors there are few practices which have been developed and used by java developers across the world. Some of those are

  1. Always clean up the resources in the finally block.
    In your code if have any IO connections open, use the finally block to close them.
  2. Always prefer specific Exceptions over generic ones
    This is good practice for development. If a generic exception is thrown it would be difficult to debug as the generic exception more than one error scenario.
  3. Document the Custom Exception
    Documenting the Custom Exception with details and specify the use-case associated with each of them. It will help in the debugging the code.
  4. Use Descriptive message while throwing Exception.
    Always set precise messages with each thrown exception.The exception’s message gets read by everyone who has to understand what had happened when the exception was reported in the log file or your monitoring tool.
  5. Catch the Most Specific Exceptions first
    Always catch the most specific exception class first and add the less specific catch blocks to the end of your list. you can see the example of the same in CatchMultipleException.java.

9. Download the Source Code

Download
You can download the full source code of this example here: Java throw Exception Example

Last updated on Aug 22, 2019

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments