×

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

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.