Throw custom exception in java

Custom exceptions in Java

You can create your own exceptions in Java and they are known as user-defined exceptions or custom exceptions.

To create a user-defined exception extend one of the above-mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor bypassing the message in String format.

MyException(String msg) < super(msg); >Or, public String toString()

Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword.

MyException ex = new MyException (); If(condition……….)

Custom Checked and Custom Unchecked

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.

Example: Custom Checked exception

The following Java program demonstrates how to create a Custom checked exception.

import java.util.Scanner; class NotProperNameException extends Exception < NotProperNameException(String msg)< super(msg); >> public class CustomCheckedException < private String name; private int age; public static boolean containsAlphabet(String name) < for (int i = 0; i < name.length(); i++) < char ch = name.charAt(i); if (!(ch >= 'a' && ch > return true; > public CustomCheckedException(String name, int age) < if(!containsAlphabet(name)&&name!=null) < String msg = "Improper name (Should contain only characters between a to z (all small))"; NotProperNameException exName = new NotProperNameException(msg); throw exName; >this.name = name; this.age = age; > public void display() < System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); >public static void main(String args[]) < Scanner sc= new Scanner(System.in); System.out.println("Enter the name of the person: "); String name = sc.next(); System.out.println("Enter the age of the person: "); int age = sc.nextInt(); CustomCheckedException obj = new CustomCheckedException(name, age); obj.display(); >>

Compile-time exception

On compiling, the above program generates the following exception.

CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown throw exName; ^ 1 error

Example: Custom unChecked exception

If you simply change the class that your custom exception inherits to RuntimeException it will be thrown at run time

class NotProperNameException extends RuntimeException < NotProperNameException(String msg)< super(msg); >>

If you run the previous program By replacing the NotProperNameException class with the above piece of code and run it, it generates the following runtime exception.

Runtime exception

Enter the name of the person: Krishna1234 Enter the age of the person: 20 Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small)) at july_set3.CustomCheckedException.(CustomCheckedException.java:25) at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)

Источник

Throw custom exception in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Java Custom Exception

Java Course - Mastering the Fundamentals

User-defined or Custom Exceptions are special-purpose exceptions, created by the developer for the particular function performed by the program. These exceptions are built to ensure that the part of the program executes in proper flow. There can be two types of Custom Exceptions namely Checked Exceptions (detected during compilation) and Unchecked Exceptions (detected during runtime).

What is Custom Exception in Java?

Exceptions in Java cover the majority of general exceptions that are bound to happen in programming. However, we are sometimes required to manipulate existing standard exceptions or introduce our exceptions as per the requirement of our use case. These are called user-defined or custom exceptions. We can create an exception by extending the Exception class in Java.

Why Use Custom Exceptions?

  • Customizing Existing Java Exceptions Let’s take an example, you developed a calculator and the user is trying to divide a number by 0. Now during runtime Java will throw an Arithmetic exception , the user won’t understand where it all went wrong and your program will crash. To avoid such a situation as a programmer you will catch this exception, and throw a custom exception informing the user that they are trying to divide a number by 0, which is invalid.
  • Generating new Java Exception — We all come across exceptions such as Enter valid Phone Number, Enter Correct Password , The Captcha text Doesn’t match, etc. All these are examples of Bussiness Logic Exceptions. These are not in-built but their presence is necessary for the application. These are developed by the programmers so that the users can understand the exact problem and then the system can function properly.

Superclass, Constructors, and Components

  • Superclass has constructor methods with no arguments, String and/or Throwable as arguments. When we pass the String message to the superclass it shows this message in exception.
  • When we catch an in-built exception and throw a custom exception, we can pass the in-built exception as a parameter to the constructor method known as Throwable. This constructor method will pass Throwable to the superclass. Thus, while printing Stack Trace the superclass will also show actual exception along with the custom exception.

superclass-constructors-and-components

  • Stack Trace — It is a report that traces the execution path of the program which is useful and debugging and identifying problems quickly.
  • Message — Explanation of the exception.

Note: Calling superclass is not mandatory, but it makes custom exceptions readable for the user.

Steps to Create a Custom Exception in Java

  1. Create your own Exception Class named InvalidInputException that extends Exception Class from java.lang .
  2. Create a Constructor Method with String statement as an argument. String as an argument allows us to custom message each time we throw an exception.
  3. Call super(statement) i.e. Constructor method of a superclass with a statement as input. This will print our custom message with the exception.

Here, we are creating our exception InvalidInputException class that extends Exception class. This takes a custom message as input.

Congrats we just created our personalized Exception which is ready to be thrown. Let’s try throwing this Exception. Let us just call a method that throws exceptions and see what a custom exception looks like.

In the above example, the justThrowException method throws InvalidInputException , this method of calling throws an exception. We call the constructor method of InvalidInputException and pass a string that explains the cause of the Exception.

In the main method, we try calling the justThrowException method and catch the exception calling the printStackTrace() method which tracks the path of Exception. We can also call e.getMessage() to know the cause of the Exception.

Types of Custom Exception in Java

Custom Exceptions are of two types.

examples-of-custom-exception-in-java

  • Custom Checked Exceptions
  • Custom Unchecked Exceptions

1. Custom Checked Exception

Checked Exceptions are the exceptions that are detected at the time of compilation. These must be handled explicitly by the developers. The code won’t compile only if these exceptions are not taken care of in other words if we ignore these exceptions (not handled with try/catch or throw the exception) then a compilation error occurs. These are caused by unexpected conditions outside the control of code like wrong input, file I/O error , etc.

Let us see how custom checked-exception works. Let us create a class where we create a FileInputStream to read a file from the computer. Suppose that the user entered a file’s name or path that is incorrect. At compile time only it will throw an exception that a file is not found and the user is unable to understand the issue. So we throw a custom FileException that explains the issue to the user and also shows the root cause.

FileException extends the Exception class. Its constructor method takes the message and Throwable as arguments. And we call super with both these parameters, thus we can print a custom message and also share the actual Exception FileNotFoundException if the file is missing. Class FileJava has the main method that has FileInputStream myFile. Now we try to give a path to Stream for the file in the try-catch block. If the file exists, try block will execute. In case the file is not present, inside the catch block we throw a custom exception that makes the program more readable. We print StackTrace and message in the output.

It is a checked exception as it identifies if the file is present or not during compilation only.

In the output, we observe FielException and its message. It also prints StackTrace, that at line 16 we are trying to initialize myFile with the path that doesn’t exist. Thus, we throw FileException which is caused due to FileNotFoundException .

2. Custom Unchecked Exception

Unchecked exceptions are exceptions that cannot be detected during compilation. The compiler checks the code in advance for the presence of any potential exceptions. These exceptions occur at runtime and can only be detected at runtime.

Let us take an example for Custom Unchecked Exception . Let us assume that there is a list of products from which the consumer is trying to fetch some item using the product key. Now if the product key is greater than the number of items in the product’s list then we throw the ProductNotFound Exception. This also explains Consumer the cause of the exception.

ProductNotFound is a class that extends the Exception class. notFound String explains the reason that the product key is invalid. The Constructor method takes no parameter. We pass the notFound String to the superclass.

Superclass prints the custom message at the time of the exception. Products class defines ProductsList which contains various products. bring() method simply returns Products at Index ProductNo-1 also called Product-key from the ProductsList array if the product-key is in the range. bring() method throws a ProductNotFound Exception if it is not valid. This is called a Checked Exception as we can only know during runtime if we have a product at a particular product-key index. In the main method, we try to fetch some random products.

In the output, as 2 was a valid Product Key, it returned Washing Machine at index 1. But 6 was an invalid Product Key, the program throws a ProductNotFound Exception.

Conclusion

  • Custom or User-defined Exceptions are designed as per the requirement of the program. Using custom Exception we can have our own Exception and a meaningful message explaining the cause of the exception.
  • We can create an exception by extending the Exception or RuntimeException class in our own Exception class. We can use the Exception.getMessage() method to understand the cause of the exception and Exception.printStackTrace() to know the root of the exception.
  • Exceptions are of two types, one that can be detected during compilation known as Checked Exceptions, and the other that can be detected only during runtime called Unchecked Exceptions.

See More

Источник

Читайте также:  Php enable maintainer zts
Оцените статью