Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

View Poll Results: Did you find the post helpful?

Voters
2. You may not vote on this poll
  • Yes

    2 100.00%
  • No

    0 0%
Results 1 to 5 of 5

Thread: Declaring your own exceptions

  1. #1

    Default Declaring your own exceptions

    You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:

    * 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.


    We can define our own Exception class as below:
    class MyException extends Exception{ 
     }

    You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

    Example:

     // File Name InsufficientFundsException.java
     import java.io.*;
     
     public class InsufficientFundsException extends Exception 
     {
       private double amount;
       public InsufficientFundsException(double amount)
       {
          this.amount = amount;
       } 
       public double getAmount()
       {
          return amount;
       }
     }


    To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.

     // File Name CheckingAccount.java
     import java.io.*;
     
     public class CheckingAccount
     {
       private double balance;
       private int number;
       public CheckingAccount(int number)
       {
          this.number = number;
       }
       public void deposit(double amount)
       {
          balance += amount;
       }
       public void withdraw(double amount) throws InsufficientFundsException 
       {
          if(amount <= balance)
          {
             balance -= amount;
          }
          else
          {
             double needs = amount - balance;
             throw new InsufficientFundsException(needs); 
          }
       }
       public double getBalance()
       {
          return balance;
       }
       public int getNumber()
       {
          return number;
       }
     }


    The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.

     // File Name BankDemo.java
     public class BankDemo
     {
       public static void main(String [] args)
       {
          CheckingAccount c = new CheckingAccount(101);
          System.out.println("Depositing $500...");
          c.deposit(500.00);
          try
          {
             System.out.println("\nWithdrawing $100..."); 
             c.withdraw(100.00);
             System.out.println("\nWithdrawing $600...");
             c.withdraw(600.00);
          }catch(InsufficientFundsException e)
          {
             System.out.println("Sorry, but you are short $"
                                      + e.getAmount());
             e.printStackTrace();
          }
        }
     }
     
     
     
    //Compile all the above three files and run BankDemo, this would produce following result:
     
    Depositing $500...
     
    Withdrawing $100...
     
    Withdrawing $600...
    Sorry, but you are short $200.0
    InsufficientFundsException
            at CheckingAccount.withdraw(CheckingAccount.java:25)
            at BankDemo.main(BankDemo.java:13)

    Source Code 2 Learn
    Last edited by weakprogrammer; June 25th, 2011 at 03:50 PM.
    Warm Regards,

    weakprogrammer

    Code 2 Learn


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Declaring your own exceptions

    Please wrap your code segments in code tags to preserver formatting. Use the # icon in Advanced.

  3. #3

    Default Re: Declaring your own exceptions

    dONE norm.

    Thanks for telling.
    Warm Regards,

    weakprogrammer

    Code 2 Learn

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Declaring your own exceptions

    Thanks. Many of us find code easier to read if its formatted.

  5. #5
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Declaring your own exceptions

    I've updated the tags to the highlight tag as the syntax highlighting makes it even easier to read.. Ideally I would like to replace the code tag with this completely.

    As for this example on Exceptions, thanks for the post. I think people will indeed find this useful

    I notice you run a blog. Feel free to contact me if you wish to host a blog here.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

Similar Threads

  1. Declaring a date
    By Akim827 in forum Java Theory & Questions
    Replies: 7
    Last Post: October 12th, 2010, 11:47 AM
  2. <..> when declaring a class
    By Asido in forum Java Theory & Questions
    Replies: 1
    Last Post: September 8th, 2010, 08:47 AM
  3. How To add my own Exceptions
    By Newtojava in forum Object Oriented Programming
    Replies: 1
    Last Post: September 2nd, 2010, 07:43 AM
  4. Java Exceptions
    By Vinceisg0d in forum Java Theory & Questions
    Replies: 2
    Last Post: March 13th, 2010, 12:25 AM
  5. Declaring variables in constructor and compiling
    By Newoor in forum Object Oriented Programming
    Replies: 3
    Last Post: December 5th, 2009, 01:07 PM

Tags for this Thread