c 1 introduction to programming and the c language

c 1 introduction to programming and the c language


DisciplinaFísica Básica I830 materiais10.237 seguidores
Pré-visualização50 páginas
handling
Here you should note that the type inherits ApplicationException and the only thing that happens is that 
there is a constructor that sends a text on to the base class\u2019s constructor. It is a very simple type, which in 
reality does not extend ApplicationException and the only purpose is to get a type that is specific for the 
current problem. I will define two additional types of exceptions, both types that inherit SetException:
public class AddException : SetException
{
public AddException()
: base("The element already exists in the set and can not be added")
{
}
}
public class RemoveException : SetException
{
public RemoveException()
: base("The element is not found in the set and can not be removed")
{
}
}
From the names and the text it is clear what they should be used for and the important thing is that 
there is the following class hierarchy are available:
Exception
ApplicationException
SetException
AddException RemoveException
I will now extend the code in the class Set, so it possibly raises an exception, but I have only shown the 
methods that have been changed:
public class Set<T> : ISet<T>
{
private T[] elems = new T[10];
private int count = 0;
public void Add(T elem)
{
if (IndexOf(elem) >= 0) throw new AddException();
if (count == elems.Length) Expand();
elems[count++] = elem;
}
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
178 
Exception handling
public void Remove(T elem)
{
int n = IndexOf(elem);
if (n < 0) throw new RemoveException();
elems[n] = elems[--count];
}
.....
}
The methods Add() and Remove() now raise an exception if the operation can\u2019t be performed. Note that 
the exceptions there are raised, is of a different type.
Below is a method that uses the class Set and catch any exceptions:
static void Test3()
{
ISet<int> A = new Set<int>();
try
{
for (int i = 0; i < 20; ++i)
{
try
{
int t = rand.Next(30);
A.Add(t);
t = rand.Next(30);
A.Remove(t);
}
catch (AddException ex)
{
Console.WriteLine(ex.Message);
}
catch (RemoveException ex)
{
Console.WriteLine(ex.Message);
}
catch (SetException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine(A);
}
}
Print(A, A.Count);
}
catch
{
Console.WriteLine(&quot;There was an error&quot;);
}
}
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
179 
Exception handling
Here are some things to be explained. First, notice that there are two try blocks: An outer outside the for 
loop, and an inner encapsulating the body of the for loop. So please note that you can have try blocks 
inside each other. In the loop, two things happens:
1. adding a random number (between 0 and 29) the set A
2. a random number is removed from the set
In both cases there may be an exception. Therefore, the code is placed in a try block. After the try block, 
there are three catch handlers, which are intended to illustrate that there may be several catch handlers 
for a try block. If the block raises an exception, the program control is transferred to the catch handler 
that matches the type of the exception raised. It is, therefore, that exceptions may have a different type, 
so that multiple catch handlers can control what happens in different situations.
Also note that the innermost try block has an associated finally handler. This will \u2013 if it is there what is 
not necessary \u2013 be performed regardless of whether there is an exception or not.
Finally, there is the outer try block. This is an example of an anonymous catch handler, and thus a catch 
handler that is executed when there is an exception and regardless of type \u2013 it catch anything.
SystemException
When an application raises an exception, it should always be of type ApplicationException or a type that 
is directly or indirectly derived from ApplicationException. The class is, as mentioned derived from the 
class Exception and there is nothing that prevents that one can raise an exception of the type Exception. 
When you should not do it, it is because there is another exception class called SystemException that are 
also derived from Exception. Exceptions of this type are intended for exceptions raised by the runtime 
system or the basic classes from the framework, and they indicate fundamental and serious problems 
where the typical handling is to terminate the program with an error message. The following hierarchy 
separates the exceptions into two categories, one category indicate failure, which typically results in that 
the program exits with an error message while the second category indicates the error caused by the 
program\u2019s environment or use, and thus an error that should be handled by the program.
ApplicationExceptionSystemException
Exception
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language 
180 
Exception handling
As an example is below shown a method which results in an error, because it are indexing outside an array:
static void Test4()
{
int[] t = { 2, 3, 5, 7, 11, 13, 17, 19 };
try
{
int s = 0;
for (int i = 0; i < 10; ++i) s += t[i];
Console.WriteLine(s);
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
Console.WriteLine(ex.GetType().BaseType.Name);
Console.WriteLine(ex.GetType().BaseType.BaseType.Name);
}
}
The result is as follows:
your chance 
to change 
the world
Here at Ericsson we have a deep rooted belief that 
the innovations we make on a daily basis can have a 
profound effect on making the world a better place 
for people, business and society. Join us.
In Germany we are especially looking for graduates 
as Integration Engineers for 
\u2022	 Radio Access and IP Networks
\u2022	 IMS and IPTV
We are looking forward to getting your application!
To apply and for all current job openings please visit 
our web page: www.ericsson.com/careers
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
181 
Comments
22 Comments
Consider as an example the following class, which you have also seen in Exam34:
using System;
using System.Text;
/*
This namespace contains several classes with miscellaneous methods.
One can perceive the namespace as a custom class library.
*/
namespace Exam42
{
/// <summary>
/// Class with static methods for text operations.
/// </summary>
public static class String
{
/// <summary>
/// Method, which cuts off a string to a maximum width.
/// If the width does not exceed the desired width,
/// the method simply returns the string unchanged.
/// </summary>
/// <param name=&quot;text&quot;>The string that must be cut</param>
/// <param name=&quot;length&quot;>The maximum width of the return string</param>
/// <returns>A string whose width is less than or equal to the length</returns>
public static string Cut(string text, int length)
{
if (text.Length > length) return text.Substring(0, length);
return text;
}
/// <summary>
///	Method	to	adjust	a	text	string	within	a	given	field	with	the	width	length.
/// If the length of the text is larger than length, the method simply
/// returns the text.
/// Otherwise the method returns a string of length length, where text
///	is	left-aligned,	and	where	the	field	is	filled	with	the	character	fill.
/// </summary>
/// <param name=&quot;text&quot;>The text to be adjusted</param>
/// <param name=&quot;length&quot;>Field width</param>
///	<param	name=&quot;fill&quot;>Fill	character</param>
/// <returns>Justifyed text</returns>
public	static	string	FillRight(string	text,	int	length,	char	fill)
{
if (text.Length >= length) return text;
StringBuilder builder = new StringBuilder(text, length);
while	(builder.Length	<	length)	builder.Append(fill);
return builder.ToString();
}
/// <summary>