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) |
Comments
Post a Comment