TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Maha
NA
0
330.1k
Creating own EXCEPTION CLASSES
Jan 30 2012 1:10 PM
This example is given to demonstrate creating your own EXCEPTION CLASSES. I wish to know importance of having static (highlighted in the example)
using System;
public class TryBankAccount
{
public static void Main()
{
BankAccount acct = new BankAccount();
try
{
acct.SetAccountNum(1234);
acct.SetBalance(-1000);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
}
//p303
public class BankAccount
{
private int accountNum;
private double balance;
public int GetAccountNum()
{
return accountNum;
}
public void SetAccountNum(int acctNumber)
{
accountNum = acctNumber;
}
public double GetBalance()
{
return balance;
}
public void SetBalance(double bal)
{
if(bal < 0)
{
NegativeBalanceException nbe = new NegativeBalanceException();
throw(nbe);
//OR throw(new NegativeBalanceException());
}
balance = bal;
}
}
public class NegativeBalanceException : ApplicationException
{
private
static
string msg = "Bank balance is negative.";
public NegativeBalanceException() : base(msg)
{
}
}
/*
Bank balance is negative.
at BankAccount.SetBalance(Double bal) in c:\documents and settings\winuser\my documents\my files\vif\visual c#\visual c# step by step\book chapters assignments\chapter8\dustbin 8\class1.cs:line 46
at TryBankAccount.Main() in c:\documents and settings\winuser\my documents\my files\vif\visual c#\visual c# step by step\book chapters assignments\chapter8\dustbin 8\class1.cs:line 13
Press any key to continue
*/
Reply
Answers (
30
)
0
Maha
0
0
330.1k
Feb 8 2012 10:44 AM
Thank you very much for your help.
Okay I will create a new thread for each new question.
0
Vulpes
0
96k
2.6m
Feb 8 2012 10:30 AM
I may have taken a slight liberty with the question here in creating a separate method to create Employee objects so we don't have to repeat the try/catch stuff 3 times:
using System;
namespace _8e5
{
class EmployeeExceptionDemo
{
static void Main(string[] args)
{
Employee emp1 = CreateEmployee("12", 4);
Employee emp2 = CreateEmployee("34", 20);
Employee emp3 = CreateEmployee("56", 60);
Console.ReadKey();
}
static Employee CreateEmployee(string IDNum, double hourlyWage)
{
Employee emp = null;
try
{
emp = new Employee(IDNum, hourlyWage);
}
catch(EmployeeException ee)
{
Console.WriteLine(ee.Message);
}
return emp;
}
}
class EmployeeException : Exception
{
public EmployeeException(string idAndPayRate) : base (idAndPayRate + " is invalid")
{
}
}
class Employee
{
public readonly string IDNum;
public readonly double hourlyWage;
public Employee(string IDNum, double hourlyWage)
{
if (hourlyWage < 6.0 || hourlyWage > 50.0)
throw new EmployeeException(String.Format("ID Number {0}, Pay Rate {1}", IDNum, hourlyWage));
this.IDNum = IDNum;
this.hourlyWage = hourlyWage;
}
}
}
Maha, would you mind creating a new thread for each new question as having to scroll through a large number of posts can get very tedious. It will also deter anybody else but me from answering the question.
0
Maha
0
0
330.1k
Feb 7 2012 7:25 PM
Attachment:
chapter8-exercises.zip
This is Q(5) of a incomplete program. Please complete it.
using System;
namespace _8e5
{
class EmployeeExceptionDemo
{
static void Main(string[] args)
{
Employee emp1 = new Employee("12", 4);
Employee emp2 = new Employee("34", 20);
Employee emp3 = new Employee("56", 60);
try
{
if (hourlyWage < 6 || hourlyWage > 50)
{
throw;
}
}
Console.ReadKey();
}
}
}
class EmployeeException
{
string id;
double payRate;
public EmployeeException(string id, double payRate)
{
}
}
class Employee
{
string IDNum;
double hourlyWage;
Employee(string IDNum, double hourlyWage);
{
}
}
0
Maha
0
0
330.1k
Feb 7 2012 9:05 AM
Thank you very much for your help.
0
Vulpes
0
96k
2.6m
Feb 7 2012 8:48 AM
The idea is that 'sqrt' should end up with a value to be printed out whether the number entered is valid or not.
To see the benefit of this, you need to answer the question exactly as it's asked:
using System;
namespace FindSquareRoot
{
class Math
{
static void Main(string[] args)
{
double sqrt;
try
{
Console.Write("Enter a number ");
double number = Convert.ToDouble(Console.ReadLine());
if (number < 0) throw new ApplicationException("Number can't be negative.");
sqrt = System.Math.Sqrt(number);
}
catch (FormatException)
{
Console.WriteLine("The input should be a number.");
sqrt = 0;
}
catch (ApplicationException nn)
{
Console.WriteLine(nn.Message);
sqrt = 0;
}
Console.WriteLine("\nThe value of sqrt is {0}", sqrt);
Console.ReadKey();
}
}
}
0
Maha
0
0
330.1k
Feb 7 2012 6:26 AM
Attachment:
chapter8-exercises.zip
This is Q(4). I wish to know answer is correct, if not please correct it. Question is requesting to set
sqrt
variable to 0. I didn't do that though program is running correctly. Please tell me the reason why ask to set
sqrt
0.
using System;
namespace FindSquareRoot
{
class Math
{
static void Main(string[] args)
{
double sqrt;
try
{
Console.Write("Enter a number ");
double number = Convert.ToDouble(Console.ReadLine());
sqrt = SqareRoot(number);
Console.WriteLine("The Sqare Root of {0} is {1}",number, sqrt);
}
catch (FormatException e)
{
Console.WriteLine("The input should be a number.");
}
catch (ApplicationException nn)
{
Console.WriteLine(nn.Message);
}
Console.ReadKey();
}
public static double SqareRoot(double number)
{
double sqrt = System.Math.Sqrt(number);
if (number < 0)
{
NegativeNumber nn = new NegativeNumber();
throw nn;
}
return sqrt;
}
}
}
public class NegativeNumber : ApplicationException
{
private static string msg = "Number can't be negative.";
public NegativeNumber() : base(msg)
{
}
}
0
Maha
0
0
330.1k
Feb 6 2012 10:45 AM
Thank you
0
Vulpes
0
96k
2.6m
Feb 6 2012 10:30 AM
Although your premium calculation code is correct, you haven't really done what the question asks - not that it's 100% clear in any case.
Here's what I'd suggest:
using System;
namespace CarInsuranceMain
{
class CarInsurance
{
static int age;
static string state;
static void CalculatePremium()
{
int cInsurance;
if((age >= 16 && age <= 80) && (state == "IL" || state == "WI"))
{
Console.WriteLine("Age: {0}", age);
if (state == "IL")
cInsurance = 100 + 3 * (100 - age);
else
cInsurance = 50 + 3 * (100 - age);
Console.WriteLine("State: {0} Car Insurance: {1}", state, cInsurance.ToString("C"));
}
else
{
ArgumentException ae = new ArgumentException();
throw ae;
}
}
static void Main(string[] args)
{
try
{
Console.Write("Enter Age ");
age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Residing State either IL/WI ");
state = Console.ReadLine().ToUpper();
Console.WriteLine();
CalculatePremium();
}
catch(FormatException fex)
{
Console.WriteLine(fex.Message);
}
catch(ArgumentException aex)
{
Console.WriteLine(aex.Message);
}
Console.ReadKey();
}
}
}
0
Maha
0
0
330.1k
Feb 6 2012 8:51 AM
Attachment:
chapter8-exercises.zip
This is Q(3). I wish to know answer is correct, if not please correct it. Please tell me why it is called
ArgumentException
. In my view as the exception is coming from
argument
in the method it is called
ArgumentException
.
using System;
namespace CarInsuranceMain
{
class Program
{
static void Main(string[] args)
{
int cInsurance, age;
try
{
Console.Write("Entre Age ");
age = Convert.ToInt32(Console.ReadLine());
Console.Write("Entre Resisding State either IL/WI ");
string state = Console.ReadLine();
if((age >= 16 && age <= 80) && (state == "IL" || state == "WI"))
{
Console.WriteLine("Age: {0}", age);
if (state == "IL" || state == "WI")
{
if (state == "IL")
cInsurance = 100 + 3 * (100 - age);
else
cInsurance = 50 + 3 * (100 - age);
Console.WriteLine("State:{0} Car Insurance: {1}", state, cInsurance.ToString("C"));
}
}
else
{
ArgumentException ae = new ArgumentException();
throw (ae);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
0
Maha
0
0
330.1k
Feb 5 2012 9:34 AM
Thank you very much for your explanation.
0
Vulpes
0
96k
2.6m
Feb 5 2012 9:20 AM
There's no benefit in using 'return' in this particular program as there's no code after the 'while' statement.
However, if there had been subsequent code which you didn't want to execute in the event of an exception, then 'return' would have been better than 'break'.
0
Maha
0
0
330.1k
Feb 5 2012 9:13 AM
In this program what is the benefit of '
return
' because without '
return
' program is producing similar result.
0
Vulpes
0
96k
2.6m
Feb 5 2012 8:38 AM
Here's how to use return to exit the Main() method and the program.
Incidentally, I don't think you're supposed to ask the user for an index because the question says:
"Write a try block in which you access each element of the array, subsequently increasing the subscript by 1".
So I've removed that part of the code:
using System;
namespace ConsoleApplication1
{
class GoTooFar
{
static void Main(string[] args)
{
int[] integer = new int[5] { 10, 20, 30, 40, 50 };
int index = 0;
while (true)
{
try
{
Console.WriteLine("Value of the integer at index {0} = {1}", index, integer[index]);
++index;
Console.WriteLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("\nNow you've gone too far.");
Console.ReadKey();
return;
}
}
}
}
}
0
Maha
0
0
330.1k
Feb 5 2012 7:39 AM
I have altered according to your suggestion. If it is correct, please show how to use 'return' to exit the Main() method.
using System;
namespace ConsoleApplication1
{
class GoTooFar
{
static void Main(string[] args)
{
int[] integer = new int[5] { 10, 20, 30, 40, 50 };
int index=0;
while (true)
{
try
{
Console.Write("Enter an index ");
index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Value of the integer {0}", integer[index]);
++index;
Console.WriteLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Now you've gone too far.");
break;
}
}
Console.ReadKey();
}
}
}
/*
Enter an index 0
Value of the integer 10
Enter an index 1
Value of the integer 20
Enter an index 2
Value of the integer 30
Enter an index 3
Value of the integer 40
Enter an index 4
Value of the integer 50
Enter an index 5
Index was outside the bounds of the array.
Now you've gone too far.
*/
0
Vulpes
0
96k
2.6m
Feb 4 2012 7:06 PM
You've done it correctly except that you haven't actually stored the 5 values in the array - you've just placed them in the temporary variable 'num'.
Instead of 'goto', I'd just use 'break' to exit the 'while' loop.
You could also use 'return' to exit the Main() method - and the program - altogether.
0
Maha
0
0
330.1k
Feb 4 2012 6:45 PM
Attachment:
chapter8-exercises.zip
This is Q(1) of my attempt. I wish to know whether it is correct, if so, is there any way to do this program without using reserved keyword
goto
.
using System;
namespace ConsoleApplication1
{
class GoTooFar
{
static void Main(string[] args)
{
int[] integer = new int[5];
int value, index;
index = 0;
while(true)
{
try
{
value = integer[index];
Console.Write("Enter an integer ");
int num = Convert.ToInt32(Console.ReadLine());
++index;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Now you've gone too far.");
goto
end;
}
}
end:
Console.ReadKey();
}
}
}
0
Vulpes
0
96k
2.6m
Feb 2 2012 9:39 AM
You use a
try/catch/finally
statement whenever you think an exception could occur which you can catch and either swallow (i.e. ignore) or take some remedial action.
You use the
throw
statement whenever you want to throw an exception (or rethrow the current exception) at a particular point in your code. Typically, you'll then catch the exception in a try/catch/finally statement or errorhandler higher up the call stack, take remedial action where possible or just log it and allow the application to terminate gracefully.
0
Maha
0
0
330.1k
Feb 2 2012 7:07 AM
In some programs exception are thrown
only
by using try catch block and in other programs exception are
thrown
by not only using try catch block but using
throw
keyword.
I wish to know when to use only try catch block and when
throw
keyword also be used.
0
Vulpes
0
96k
2.6m
Feb 1 2012 4:30 PM
The purpose is to customize how an application runs or to tell it what to do.
A good example of command line arguments is the C# compiler csc.exe:
http://msdn.microsoft.com/en-us/library/6ds95cz0(VS.71).aspx
0
Maha
0
0
330.1k
Feb 1 2012 3:05 PM
What is the purpose of using command line arguments
0
Vulpes
0
96k
2.6m
Feb 1 2012 2:54 PM
It's not taking input from the console in the normal way i.e.
after
the application has started running.
Instead, command line arguments (separated by spaces) are being passed to the application,
when it starts
, and stored in the 'args' string array parameter to the Main() method.
The code you've shown then converts the first and second command line arguments to ints.
0
Maha
0
0
330.1k
Feb 1 2012 2:35 PM
http://www.youtube.com/watch?v=Zek94pOkfbU
In the above YouTube I have seen the following function taking input from keyboard.
int n1 = Convert.ToInt32(
args[0]
);
int n2 = Convert.ToInt32(
args[1]
);
Normally we use function like this int n1 = Convert.ToInt32(
Console.ReadLine()
);
I wish to know the differences.
0
Vulpes
0
96k
2.6m
Feb 1 2012 9:15 AM
The type-testing operator 'is' checks whether an object is of a particular type, or is a sub-type thereof. It's documented on MSDN here:
http://msdn.microsoft.com/en-us/library/scekt9xw.aspx
So what we're doing is checking whether 'error' is a DivideByZeroException object:
http://msdn.microsoft.com/en-us/library/system.dividebyzeroexception.aspx
If it is, we correct the error by setting the denominator to 1 and 'retry' the try statement.
Although I haven't done it this way because I'm not sure what you're allowed to change or supposed to know at this stage in your studies, in practice this would normally be dealt with by having two catch clauses:
using System;
namespace TwoErrors2
{
class Program
{
static void Main(string[] args)
{
int num = 13, denom = 0, result;
int[] array = { 22, 33, 44 };
retry:
try
{
result = num / denom; // First try
result = array[num]; // Second try
}
catch (DivideByZeroException error) // catches the first error as more specific
{
Console.WriteLine(error.Message);
denom = 1;
goto retry;
}
catch (Exception error) // catches the second error
{
Console.WriteLine(error.Message);
}
Console.ReadKey();
}
}
}
0
Vulpes
0
96k
2.6m
Jan 31 2012 3:59 PM
There are basically two ways whereby you could catch both exceptions:
// First way - using two try statements
using System;
namespace TwoErrors2
{
class Program
{
static void Main(string[] args)
{
int num = 13, denom = 0, result;
int[] array = { 22, 33, 44 };
try
{
result = num / denom; // First try
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
try
{
result = array[num]; // Second try
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
Console.ReadKey();
}
}
}
// Second way - using retry after correcting first error
using System;
namespace TwoErrors2
{
class Program
{
static void Main(string[] args)
{
int num = 13, denom = 0, result;
int[] array = { 22, 33, 44 };
retry:
try
{
result = num / denom; // First try
result = array[num]; // Second try
}
catch (Exception error)
{
Console.WriteLine(error.Message);
if(error is DivideByZeroException)
{
denom = 1;
goto retry;
}
}
Console.ReadKey();
}
}
}
0
Maha
0
0
330.1k
Jan 31 2012 2:57 PM
In this program two exceptions are occurring. First try is caught by the catch block and second try is skipped. I wish to know whether this program can be modified to catch the both exceptions.
using System;
namespace TwoErrors2
{
class Program
{
static void Main(string[] args)
{
int num = 13, denom = 0, result;
int[] array = { 22, 33, 44 };
try
{
result = num / denom;
// First try
result = array[num];
// Second try
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
Console.ReadKey();
}
}
}
0
Vulpes
0
96k
2.6m
Jan 30 2012 6:38 PM
The only other way to do it would be to change the constructor so that it takes a string 'msg' argument:
public class BankAccount
{
private int accountNum;
private double balance;
public int GetAccountNum()
{
return accountNum;
}
public void SetAccountNum(int acctNumber)
{
accountNum = acctNumber;
}
public double GetBalance()
{
return balance;
}
public void SetBalance(double bal)
{
if(bal < 0)
{
NegativeBalanceException nbe =
new NegativeBalanceException("Bank balance is negative");
throw(nbe);
//OR throw(new NegativeBalanceException());
}
balance = bal;
}
}
public class NegativeBalanceException : ApplicationException
{
//private static string msg = "Bank balance is negative.";
public NegativeBalanceException(string msg) : base(msg)
{
}
}
0
Maha
0
0
330.1k
Jan 30 2012 5:52 PM
Is there any way to do like this because this is more understandable.
using System;
public class TryBankAccount
{
public static void Main()
{
BankAccount acct = new BankAccount();
try
{
acct.SetAccountNum(1234);
acct.SetBalance(-1000);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
}
//p303
public class BankAccount
{
private int accountNum;
private double balance;
public int GetAccountNum()
{
return accountNum;
}
public void SetAccountNum(int acctNumber)
{
accountNum = acctNumber;
}
public double GetBalance()
{
return balance;
}
public void SetBalance(double bal)
{
if (bal < 0)
{
BalanceException nbe = new BalanceException();
nbe.Set______("Bank balance is negative.");
//???????????????
}
balance = bal;
}
}
public class BalanceException : ApplicationException
{
//private static string msg = "Bank balance is negative.";
public BalanceException() : base(msg)
{
}
}
0
Vulpes
0
96k
2.6m
Jan 30 2012 4:11 PM
I mean that NegativeBalanceException's constructor doesn't have any parameters so, in order for it to pass 'msg' to its base class's constructor, 'msg' needs to have been initialized elsewhere.
This can't be in an instance field (if you omit 'static' and try and compile you'll see why) and so has to be in a static field.
0
Maha
0
0
330.1k
Jan 30 2012 3:58 PM
As 'msg' is not being passed as an argument to the constructor
, the only way that this can be achieved is to use a static field. Static fields are guaranteed to have been initialized by the system before any instance constructor executes.
Could you explain me please what is the meanig of the highlighted one.
0
Vulpes
0
96k
2.6m
Jan 30 2012 2:13 PM
As you're passsing 'msg' to the base class's constructor, 'msg' needs to have been assigned to before the code in the constructor body executes.
As 'msg' is not being passed as an argument to the constructor, the only way that this can be achieved is to use a static field. Static fields are guaranteed to have been initialized by the system before any instance constructor executes.
GUI problem try #4
Classes and objects really hard