All TalkersCode Topics

Follow TalkersCode On Social Media - A Social Media Network for developers Join Now ➔

User Defined Exception In Java

Last Updated : Mar 11, 2024

User Defined Exception In Java

In this article we will show you the solution of user defined exception in java, the exceptions created per our use case and thrown using the throw keyword are user-defined exceptions, and such exceptions are derived classes of the Exception class from the java.lang package.

Java includes a few built-in specific exemptions, that are further classified as compile-time as well as runtime exceptions.

We're in a good mood until with us be using case is satisfied through one of the built in specific exemptions,but what if there's not an exception that fits with us needs?

Java allows us to create our possess exceptions, which are essentially derived classes of The exception.

Constructing our own Exception has been referred to as a custom or user-defined exception. Java custom exceptions can be used to tailor the exception to the needs of the user.

In layman's terms, a User-Defined Exception as well as custom exception is created by creating your someone else's exception class as well as trying to throw that exception using'throw' keyword.

Java exceptions cover nearly all of the common types of exceptions that can occur in programming. Sometimes, however, we need to make exceptions for ourselves.

Here are a few reasons why you should use custom exceptions:

  • To catch and manage the subset of existing Java exception.
  • Errors in business logic This includes both business logic and workflow exceptions.

It aids application users and programmers in understanding the specific problem.

Exception as well as its subclasses are a type of Throwable that represents conditions which a reasonable implementation may wish to catch.

Step By Step Guide On User Defined Exception In Java :-

class TalkersCode {
 public Exception(String s)
public class demo{
 public static void main(String args[])
     try {
         throw New My Exception("TalkersCode");
     catch (My Exception ex) {
  1. The following step involves creating a class named TalkersCode extends Exception.
  2. The following step is to write a exception function.
  3. As a result, as a string argument, a public static void main has been created.
  4. Then we create a try and catch statement.
  5. We then end the programme.

Conclusion :-

I hope this article on user defined exception in java helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Riya

A recent graduate with a Bachelor of Technology (B.Tech) in Computer Science from India. She is passionate about leveraging technology to solve real-world problems. With a strong foundation and experience in programming languages such as Python, Django, HTML, CSS, and JavaScript, java, php and have honed her skills through hands-on projects and coursework.

Follow Riya On Linkedin 🡪