DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Why Do We Need Exceptions in Code?

Why Do We Need Exceptions in Code?

Murat Gungor user avatar by
Murat Gungor
CORE ·
Apr. 20, 20 · Web Dev Zone · Tutorial
Like (6)
Save
Tweet
4.19K Views

Join the DZone community and get the full member experience.

Join For Free

Assume you have the following Bank class. In this code, the withdraw method is our main focus. Its job is to deduct a given amount from the balance and then return the updated balance.

C++
 




x
14


 
1
class Bank {
2
public:
3
    Bank(double balance = 0) {
4
        this->balance = balance;
5
    }
6

          
7
    double withdraw(double amount) {
8
        balance = balance - amount;
9
        return balance;
10
    }
11

          
12
private:
13
    double balance;
14
};



As you notice, it can return only a double. I would say that this function can only speak in "double" language, poor function. 

Currently, withdraw function can speak only one language,
the"return type" language 

There is a banking rule waiting to be implemented, which is "an account overdraft should not be allowed". For this rule, there is one solution we can silently return the current balance without deducing the amount. 

C++
 




xxxxxxxxxx
1


 
1
double withdraw(double amount) {
2
    if (balance < amount)
3
        return balance;
4
    balance = balance - amount;
5
    return balance;
6
}



But, this solution does not inform the client (in this case the main method) about the reason why the balance is not changed; actually, it says nothing to the client. The client has to figure out whether the request granted or not.

If the client notices the balance did not change, it can only guess! 

Possible reasons could be:

  • There is a daily limit? 
  • The balance is not adequate?
  • There is a minimum balance rule? 

But poor function cannot express itself. It cannot speak any other language: It can only speak (return) in "double" language.

With the exception mechanism,
a function can speak many other languages.

Look at the code below. Now, our withdraw function can speak "string" language as well. Now, it can express more than before, yay!! 

C++
 




x


 
1
class Bank {
2
public:
3
    Bank(double balance = 0) {
4
        this->balance = balance;
5
    }
6

          
7
    double withdraw(double amount) {
8
        if (balance < amount)
9
            throw string("Balance is not enough");
10

          
11
        balance = balance - amount;
12
        return balance;
13
    }
14

          
15
private:
16
    double balance;
17
};
18

          
19
private:
20
    double balance;
21
};
22

          
23
int main()
24
{
25
    Bank checking(100);
26
    try {       
27
        cout << "Balance after withdraw: $" << checking.withdraw(120) << endl;
28
        cout << "Thank you" << endl;
29
    }
30
    catch (string exceptionMessage) {
31
        cout << "Error Ocurred: " << exceptionMessage << endl;
32
    } 
33
}



If there is a daily limit, we can now implement it, and we can inform the client if it's violated. Let's look at the code below.

C++
 




xxxxxxxxxx
1
22


 
1
const int DAILY_LIMIT = 30;
2

          
3
class Bank {
4
public:
5
    Bank(double balance = 0) {
6
        this->balance = balance;
7
    }
8

          
9
    double withdraw(double amount) {
10
        if ( amount > DAILY_LIMIT)
11
            throw string("Daily limit is exceeded");
12

          
13
        if (balance < amount)
14
            throw string("Balance is not enough");      
15

          
16
        balance = balance - amount;
17
        return balance;
18
    }
19

          
20
private:
21
    double balance;
22
};


Exception keeps your client in the know

Your client has a right to know why something has not happened, or where did the client make a mistake. Exception enables your client in the know. 

Exception enables your function to express more than the "return type" value. 

Exception enables your function to speak in any languageD

Published at DZone with permission of Murat Gungor. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Geo What? A Quick Introduction to Geo-Distributed Apps
  • Get Started With Kafka and Docker in 20 Minutes
  • GraphQL in Enterprise: What It Takes to Build, Deploy, and Monitor a New Enterprise GraphQL Service
  • Why Blockchain Technology Is the Future of Data Storage

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo