Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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) { } }
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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) { } }
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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(); } } }
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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(); } } }
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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:
So what we're doing is checking whether 'error' is a DivideByZeroException object:
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(); } } }
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
What is the purpose of using command
line arguments
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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(); } } }
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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. */
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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; } } } } }
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
In this program what is the benefit of 'return' because without 'return' program is producing similar result.
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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'.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
Thank you very much for your explanation.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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(); } } }
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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(); } } }
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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) { } }
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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(); } } }
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
Thank you very much for your help.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
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); {
} }
|
|
|
|
|
|
Vulpes
posted
5113 posts
since
Feb 28, 2011
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
Maha
posted
809 posts
since
Aug 13, 2006
from
|
|
Re: Creating own EXCEPTION CLASSES
|
|
|
|
|
|
|
|
|
|
|
Thank you very much for your help. Okay I will create a new thread for each new question.
|
|
|
|
|
|