Java/J2EE and SOA (305 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (45 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (304 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What are User Defined Exceptions in Java?

Published on Aug 07,2019 19 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

An exception is a problem that arises during the execution of a program. Java, being one of the most popular object-oriented language, provides a powerful mechanism to handle these exceptions. In this article, I will give you a brief into User-Defined Exceptions in Java.

Below topics are covered in this article:

  • What are Exceptions?
  • User-Defined Exceptions

Let’s get started!

What are Exceptions?

An exception is a sudden and an unexpected event which leads to the sudden termination of the program during execution of a program that is at the runtime of a program. Below snapshot represents the execution flow of handling an exception.

Exception flow - User Defined Exceptions in java - Edureka

We all someday or the other must-have encountered these exceptions which we had to fix in order to run the program. So we need to know about these types of exceptions first so that when occurred we can deal with these in no time.

Exceptions using Try-Catch block:

class MyException1 extends Exception{
   String str1;
   
   MyException1(String str2) {
	str1=str2;
   }
   public String toString(){ 
	return ("MyException Occurred: "+str1) ;
   }
}
 
class Example1{
   public static void main(String args[]){
	try{
		System.out.println("Starting of try block");
		throw new MyException1("This is error Message");
	}
	catch(MyException1 exp){
		System.out.println("Catch Block") ;
		System.out.println(exp) ;
	}
   }
}

Here in the above snippet, I have demonstrated the use of try-catch block and how we can throw exceptions using that. The throw keyword is used to throw the exception by the user. IO Exception is used for this exception handling. The user-defined exception must contain a custom exception class. In the code, we have used a parameterized constructor which displays (This is error Message).

OUTPUT:

Starting of try block
Catch Block
MyException1 Occurred: This is error Message

 

Without using Try-Catch block

class InvalidProductException extends Exception
{
    public InvalidProductException(String s)
    {
        // Call constructor of parent Exception
        super(s);
    }
}
 
public class Example1
{
   void Check(int weight) throws InvalidProductException{
	if(weight<100){
		throw new InvalidProductException("Product Invalid");
	}
   }
   
    public static void main(String args[])
    {
    	Example1 obj = new Example1();
        try
        {
            obj.productCheck(60);
        }
        catch (InvalidProductException ex)
        {
            System.out.println("Caught the exception");
            System.out.println(ex.getMessage());
        }
    }
}

In this example, I am throwing the exception using the method. So here the throws keyword is used in the function signature or else it will show us an error.

Output

Caught the exception
Product Invalid

Basically, that’s how it works. This brings us to the end of our blog on User Defined Exceptions in Java. I hope you found this blog informative and added value to your knowledge.

Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “User Defined Exceptions in Java ” blog and we will get back to you as soon as possible.  

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.