Skip to main content

user defined exceptions in java with example

The built-in exceptions in java are not able to describe a certain situation. In such cases, like the built-in exceptions, the user(programmer) can also create his own exceptions which are called 'User-defined exceptions'. The following steps are followed in creation of user-defined exceptions.
  • The user should create an exception class as a subclass to Exception class. Since all exceptions are subclasses of Exception class, the user should also make his class a subclass to it.
1
class MyException extends Exception
  • The user can write a default constructor in his own exception class. He can use it in case he does not want to store any exceptions details. If the user does not want to create an empty object to his exception class, he can eliminate writing the default constructor.

1
MyException() {}
  • The user can create a parametrised constructor with a string as a parameter. He can use this to store exception details. He can call super class (Exception) constructor from this and send the string there.
1
2
3
MyException(String str){
    super(str);  //call exception class constructor and store str there.
}
  • When the user wants to raise his own exception, he should create an object to his exception class and throw it using throw clause,
1
2
MyException me = new MyException("Exception Data");
throw me;

       Here is the example of user defined exception. Users can create their own exception classes by extending the Exception class and thrown by using the throw keyword.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.javatbrains.exceptions;

/*This class represents the Users own exception class.*/
public class MyOwnException extends Exception {
     // store account information
     private static int acc[] = { 101, 102, 103, 104, 105 };

     private static String name[] = { "Subba", "Reddy", "Samba", "Rama", "Amar"};
     private static double bal[] = { 1000.00, 1200.00, 1290.00, 1500.00, 168.00 };

     // default constructor
     MyOwnException() {
     }

     // Parametrized Constructor
     MyOwnException(String str) {
          super(str);
     }

     // write main()
     public static void main(String[] args) {
          try{
              // display the heading from the table
              System.out.println("AccNo"+ "\t"+ "Customer"+ "\t"+ "Balance");

              // display actual account information
              for(inti = 0; i <5; i++) {
                   System.out.println(acc[i] + "\t"+ name[i] + "\t\t"+ bal[i]);

                   // display own exception if balance <1000
                   if(bal[i] <1000) {
                        MyOwnException me = new MyOwnException(
                                  "Balance amount is less");
                        throwme;
                   }
              }
          } catch(MyOwnException me) {
              me.printStackTrace();
          }
     }

}
OutPut:
      AccNo   Customer   Balance
       101     Subba     1000.0
       102     Reddy     1200.0
       103     Samba     1290.0
       104     Rama      1500.0
       105     Amar      168.0
      com.javatbrains.exceptions.MyOwnException: Balance amount is less
     at     com.javatbrains.exceptions.MyOwnException.main(MyOwnException.java:32)

Do you know?

Comments

Popular posts from this blog

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Prime, Fibonacci and Factorial number with example in java

Prime number, Fibonacci series and Factorial number programs are most commonly asked questions in interview. Read this article to know what is and how to write programs for prime number, fibonacci series and factorial number. Prime Number: prime number is natural number greater than 1 that has no positive divisor other than 1 and itself. A natural number greater than 1 is not a prime number, is called Composite number . For example, 7 is a prime number. Because it can divide with 1 and 7 only. Where as 8 is composite number. Since it has the divisor 2 and 4 in addition to the 1 and 8. The below example represents the finding the passing number is prime number or not. If the passing number is prime number it will print true otherwise it will print false. package com . javatbrains . practice ; public class PrimeNumber { public boolean isPrimeNumber ( int number ) { if ( number <= 1 ) return false ; // There's only one ...

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...