Learn Java by Example: Java Program to Create custom exception

Hits: 14

Java Program to Create custom exception

In this example, we will learn to create custom checked and unchecked exception in Java.

 


Example 1: Java program to create custom checked exception


import java.util.ArrayList;
import java.util.Arrays;

// create a checked exception class
class CustomException extends Exception{
  public CustomException(String message){
    // call the constructor of Exception class
    super(message);
  }
}

class Main{

  ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript"));

  // check the exception condition
  public void checkLanguage(String language) throws CustomException {

    // throw exception if language already present in ArrayList
    if(languages.contains(language)) {
      throw new CustomException(language + " already exists");
    }
    else {
      // insert language to ArrayList
      languages.add(language);
      System.out.println(language + " is added to the ArrayList");
    }
  }

  public static void main(String[] args){

    // create object of Main class
    Main obj = new Main();

    // exception is handled using try...catch
    try {
      obj.checkLanguage("Swift");
      obj.checkLanguage("Java");
    }

    catch(CustomException e) {
      System.out.println("[" + e + "] Exception Occured");
    }
  }
}

Output

Swift is added to the ArrayList
[CustomException: Java already exists] Exception Occured

In the above example, we have extended the Exception class to create a custom exception named CustomException. Here, we call the constructor of Exception class from the CustomException class using super() keyword.

Inside the method checkLanguage(), we have checked the exception condition, and if the exception occurs, the try..catch block handles the exception.


Example 2: Create custom unchecked exception class


import java.util.ArrayList;
import java.util.Arrays;

// create a unchecked exception class
class CustomException extends RuntimeException{
  public CustomException(String message){
    // call the constructor of RuntimeException
    super(message);
  }
}

class Main{

  ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript"));

  // check the exception condition
  public void checkLanguage(String language){

    // throw exception if language already present in ArrayList
    if(languages.contains(language)) {
      throw new CustomException(language + " already exists");
    }
    else {
      // insert language to ArrayList
      languages.add(language);
      System.out.println(language + " is added to the ArrayList");
    }
  }

  public static void main(String[] args){

    // create object of Main class
    Main obj = new Main();

    // check if language already present
    obj.checkLanguage("Swift");
    obj.checkLanguage("Java");
  }
}

Output


Swift is added to the ArrayList
Exception in thread "main" CustomException: Java already exists
        at Main.checkLanguage(Main.java:21)
        at Main.main(Main.java:37)

In the above example, we have extended the RuntimeException class to create an unchecked custom exception class.

Here, you can notice that, we haven’t declared any try…catch block. It is because the unchecked exception is checked at runtime.

Besides that, other functionality of unchecked exception is similar to the above mentioned program.

 

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.