×

Java Custom Exception

Java Custom Exception

Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java throw keyword is used to throw the Java Custom Exception. One can throw a checked as well as an unchecked custom exception.

Throwing a Custom Checked Exception

For creating a custom-checked exception, the Java Exception class must be extended. The custom-checked exception is detected at the compile time. The following program illustrates how one can raise a custom-checked exception.

FileName: CustomCheckException.java

 class NoProperNameException extends Exception
{
   // constructor of the class NoProperNameException
   NoProperNameException(String m)
   {
      // invoking the constructor of the Exception class
      // to display the desired message
      super(m);
   }
}
public class CustomCheckException
{
private String stuName;
private int stuAge;
// a method for checking the string s contains any letter other than small letter or not
public boolean containsAlphabet(String s)
{
  // size of the string s
  int size = s.length();
   // iterating over the characters of the string s
  for (int i = 0; i < size; i++)
  {
     char c = s.charAt(i);
     if (!(c >= 'a' && c <= 'z'))
     {
        // we found a letter which not within range of a to z (all small letters)
        return false;
     }
  }
  return true;
}
// declaring that the constructor may throw the NoProperNameException
public CustomCheckException(int age, String name) throws NoProperNameException
{
  if(!containsAlphabet(name) && name != null)
  {
     // the string name contains at least one letter, which is not a small letter
     String str = "The name should be proper (Should only contain characters ranging from a to z (all small))";
     NoProperNameException obj = new NoProperNameException(str);
     throw obj;
  }
  this.stuName = name;
  this.stuAge = age;
}
// method for displaying the name and age of student
public void display()
{
  System.out.println("The Student's name is: "+ this.stuName);
  System.out.println("The Student's age is: "+ this.stuAge);
}
// main method
public static void main(String argvs[])
{
  String names[] = {"amit", "Sumit"};
  int ages[] = {34, 44};
  // calculating size of the names array
  int size = names.length;
  for(int i = 0 ; i < size; i++)
  {
  // try-catch block for handling any custom exception
  try
  {
    // instantiating the class CustomCheckException
    CustomCheckException obj = new CustomCheckException(ages[i], names[i]);
    // method's name
    obj.display();
  }
  catch(NoProperNameException expn)
  {
   System.out.println("In the catch block " + expn);    
  }
  }
}
} 

Output:

 The Student's name is: amit
The Student's age is: 34
In the catch block NoProperNameException: The name should be proper (Should only contain characters ranging from a to z (all small)) 

Explanation:The above program is written in such a way that it only raises the custom exception when anything other than a small letter is passed.The second string of the array names contains a capital letter ‘S’, and because of it, the custom exception is raised for the second string “Sumit”.

Throwing a Custom Un-Checked Exception

Un-checked exceptions are those exceptions that are checked at the runtime. To throw an un-checked exception, the class RuntimeException must be extended. Let’s observe the following program for a better understanding.

FileName: CustomCheckException1.java

 class NoCompileTimeException extends RuntimeException
{
   // constructor of the class NoCompileTimeException
   NoCompileTimeException(String m)
   {
      // invoking the constructor of the Exception class
      // to display the desired message
      super(m);
   }
}
public class CustomCheckException1
{
// a method for checking whether the number n is greater than 20 or not
public boolean isGreaterThanTwenty(int n)
{
    if(n > 20)
    {
        return true;
    }
    return false;
}
// declaring that the constructor may throw the NoCompileTimeException
public CustomCheckException1(int N) throws NoCompileTimeException
{
  if(isGreaterThanTwenty(N))
  {
     // the string name contains at least one letter, which is not a small letter
     String str = "The numbers should be either less than or greater than 20";
     NoCompileTimeException obj = new NoCompileTimeException(str);
     throw obj;
  }
}
// method for displaying the numbers
public void display(int n)
{
  System.out.println("The num: "+ n + " is the valid number");
}
// main method
public static void main(String argvs[])
{
  // input array that contains only numbers
  int numArr[] = {34, 44, 1, 7, 9, 0, 67, 34, 2, 71};
  // calculating size of the numArr array
  int size = numArr.length;
  // iterating over numbr array
  for(int i = 0 ; i < size; i++)
  {
  // try-catch block for handling any custom exception
  try
  {
    // instantiating the class CustomCheckException1
    CustomCheckException1 obj = new CustomCheckException1(numArr[i]);
    // invoking the method display()
    // only gets invoked when there is no exception raised in the try block
    obj.display(numArr[i]);
  }
  catch(NoCompileTimeException expn)
  {
   System.out.println("In the catch block " + expn);    
  }
  }
}
} 

Output:

 In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20
In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20
The num: 1 is the valid number
The num: 7 is the valid number
The num: 9 is the valid number
The num: 0 is the valid number
In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20
In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20
The num: 2 is the valid number
In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20 

Explanation: The above program throws the exceptions when it encounters a number greater than 20.


Related Topics

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 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.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.