Solved

C#: How to manually throw exceptions

Posted on 2014-10-02
9
394 Views
Last Modified: 2014-10-02
The code I'm working with has an existing try catch block. The catch block is below. In the try block, I need to manually throw an exception if a condition is met.

catch (Exception ex)
{
      ...
      ImportStatus.Append(ex.Message);
      ...
}

What is the correct way to throw an exception? Will this work? The reason I ask is because the catch block seems to accept a single parameter of type Exception. But I'm passing a string, so that's why I'm a bit confused on how to properly throw an exception with a string message.

string errorMsg = "This is an error.";
throw new Exception(errorMsg);

Open in new window

0
Comment
Question by:pzozulka
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40357497
When used in a try / catch the exception is if one of your lines of code throws an error:

eg

try

{
   int x = 0;
   int y = 10 / x;
}
 catch (Exception ex)
{
   //ex will be divide by 0 generated by the second line.  
}

You can create your own exceptions if you have custom classes, throwing them for others to catch.
0
 
LVL 8

Author Comment

by:pzozulka
ID: 40357517
Right, but what if I say the following in the try block:
throw new Exception("Address length is too long");

Open in new window

Will this be caught by the catch block?
0
 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 200 total points
ID: 40357525
Yes, it should be.

Note that the first string is the exception message,

and there's an overloaded function of new Exception(string, string) which is Message / InnerExceptionMessage.
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 34

Assisted Solution

by:it_saige
it_saige earned 100 total points
ID: 40357539
You can also catch specific exceptions in a quasi-chain (remember your exception order, Visual Studio usually does a good job of alerting you if you have an exception out of order).  What I mean by quasi-chain is that when you catch that exception the code does not check for additional exceptions in the chain.
		/// <summary>Retrieves an IP address from the local addresslist of the instantiator</summary>
		public static IPAddress GetIp()
		{
			try
			{
				var m_lprops = IPGlobalProperties.GetIPGlobalProperties();
				var m_address = new IPAddress(0);

				// If there are no local IP global properties, return a null value.
				if (m_lprops == null)
				{
					Globals.LogEntry(MethodBase.GetCurrentMethod(), "There are no local ip global properties.");
					return null;
				}

				// If no network connection is available, return a null value.
				if (!NetworkInterface.GetIsNetworkAvailable())
				{
					Globals.LogEntry(MethodBase.GetCurrentMethod(), "There are no active network connections available.");
					return null;
				}

				// If a network connection is available (marked as up and is not a loopback or tunnel interface), try to return the IPAddress object associated with the network connection.
				var m_adapters = NetworkInterface.GetAllNetworkInterfaces();

				// If there are no network connections, return a null value.
				if (m_adapters == null || m_adapters.Count() < 1)
				{
					Globals.LogEntry(MethodBase.GetCurrentMethod(), "There are no network connections available.");
					return null;
				}

				foreach (var m_adapter in m_adapters)
				{
					// Filter to exclude network interfaces that are not up [it can transmit data packets].  If an adapter is excluded, fall out of the loop.
					if (m_adapter.OperationalStatus != OperationalStatus.Up)
					{
						Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0} has an operational status of {1}.  This adapter will not be used.", 
							m_adapter.Description, m_adapter.OperationalStatus));
						continue;
					}

					// Filter to exclude network interfaces that do not support Internet Protocol version 4.  If an adapter is excluded, fall out of the loop.
					if (!m_adapter.Supports(NetworkInterfaceComponent.IPv4))
					{
						Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0} supports IPv4 - {1}.  This adapter will not be used.",
							m_adapter.Description, !m_adapter.Supports(NetworkInterfaceComponent.IPv4)));
						continue;
					}

					// Filter to exclude loopback network interfaces and unknown network interfaces.  If an adapter is excluded, fall out of the loop.
					if (m_adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback || m_adapter.NetworkInterfaceType == NetworkInterfaceType.Unknown)
					{
						Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0} is a/an {1} type.  This adapter will not be used.", 
							m_adapter.Description, m_adapter.NetworkInterfaceType));
						continue;
					}

					// Retrieve the properties of any adapters that meet the filter requirements.
					var m_props = m_adapter.GetIPProperties();

					// If there are no properties for this adapter, fall out of the loop.
					if (m_props == null)
					{
						Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("There are no properties for adapter - {0}.  This adapter will not be used.", m_adapter.Description));
						continue;
					}

					// Filter to exclude network adapters that have no gateway address assigned to them.  If an adapter is excluded, fall out of the loop.
					if (m_props.GatewayAddresses.All(_gateway => _gateway.Address == new IPAddress(0)))
					{
						Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0} has no gateway address(es) assigned - {1}.  This adapter will not be used.", 
							m_adapter.Description, m_props.GatewayAddresses.All(_gateway => _gateway.Address == new IPAddress(0))));
						continue;
					}

					// Retrieve the IPv4 properties of any adapters that meet the filter requirements
					var m_ipv4props = m_props.GetIPv4Properties();

					// Filter to exclude network adapters that have an automatice private addressing (APIPA) address assigned to them.  If an adapter is excluded, fall out of the loop.
					if (m_ipv4props.IsAutomaticPrivateAddressingActive)
					{
						Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0} has an Automatic Private Addressing (APIPA) address assigned.  This adapter will not be used.", 
							m_adapter.Description));
						continue;
					}

					// Retrieve the unicast addresses of any network adapters that meet the filter requirements.
					var m_unicastIPs = m_props.UnicastAddresses;

					// If there are no unicast ip addresses, fall out of the loop.
					if (m_unicastIPs == null)
					{
						Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0} has no unicast address(es) assigned.  This adapter will not be used.", m_adapter.Description));
						continue;
					}

					foreach (var m_unicastIP in m_unicastIPs)
					{
						// Filter to exclude unicast addresses that do not have an IPv4 Subnet mask.  If a unicast address is excluded, fall out of the loop.
						if (m_unicastIP.IPv4Mask == null)
						{
							Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0} has no IPv4 subnet mask.  This adapter will not be used.", m_adapter.Description));
							continue;
						}

						// Filter to exclude unicast addresses that are not valid and unrestricted.  If a unicast address is excluded, fall out of the loop.
						if (m_unicastIP.DuplicateAddressDetectionState != DuplicateAddressDetectionState.Preferred)
						{
							Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0}'s duplicate detection state is {1}.  This adapter will not be used.", 
								m_adapter.Description, m_unicastIP.DuplicateAddressDetectionState));
							continue;
						}

						//// Filter to exclude virtual netork addresses.  If a unicast address is excluded, fall out of the loop.
						//if (m_unicastIP.AddressPreferredLifetime == UInt32.MaxValue)
						//{
						//     Variables.FileLogger.RecordMessage(string.Format("Methods.GetIpAlternative: {0}'s unicast address {1} is a virtual address.  This adapter will not be used.", m_adapter.Description, m_unicastIP.Address), Log.MessageType.Informational);
						//     continue;
						//}

						// Filter to exclude addresses that are not IPv4 Addresses.  If a unicast address is excluded, fall out of the loop.
						if (m_unicastIP.Address.AddressFamily != AddressFamily.InterNetwork)
						{
							Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("{0}'s unicast address {1} has an address family of {2}.  This adapter will not be used.",
								m_adapter.Description, m_unicastIP.Address, m_unicastIP.Address.AddressFamily));
							continue;
						}

						// Retrieve the IPAddress from the network interface.
						m_address = m_unicastIP.Address;

						Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("Using adapter {0} with a unicast address of {1}.", m_adapter.Description, m_address));
					}

					if (BitConverter.ToUInt32(m_address.GetAddressBytes(), 0) != BitConverter.ToUInt32(new IPAddress(0).GetAddressBytes(), 0))
						break;
				}

				return BitConverter.ToUInt32(m_address.GetAddressBytes(), 0) == BitConverter.ToUInt32(new IPAddress(0).GetAddressBytes(), 0) ? null : m_address;
			}
			catch (NetworkInformationException ex)
			{
				// A windows system function call failed.
				Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("Network Information Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message), MessageType.Error);
				return null;
			}
			catch (PlatformNotSupportedException ex)
			{
				// This property is not valid on computers running operating systems earlier than Windows XP.
				Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("Platform Not Supported Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message), MessageType.Error);
				return null;
			}
			catch (Exception ex)
			{
				// Generic exception.
				Globals.LogEntry(MethodBase.GetCurrentMethod(), string.Format("Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message), MessageType.Error);
				return null;
			}
		}

Open in new window


Above I catch three different exceptions.  If an exception is thrown that is not a NetworkInformationException or a PlatformNotSupportedException then it naturally falls through to a standard Exception (since all Exceptions inherit from System.Exception).

By catching multiple exceptions you can handle different cases of failures.

-saige-
0
 
LVL 44

Assisted Solution

by:AndyAinscow
AndyAinscow earned 100 total points
ID: 40357546
Just don't forget using a try...catch is expensive in terms of resources the app uses.  Throwing an exception inside your try block so it is caught within the same method just begs the question why?  Often a slight rethink of your code will allow you to achieve the same.

eg consider the following.
if(xxx)
  throwException
....
catch
  report the exception.


with
if(xxx)
  {
  report the 'exception'
  }
else
  {
  perform the code
  }

The second is more efficient and does the same job as the first.
0
 
LVL 8

Author Comment

by:pzozulka
ID: 40357582
This is an existing try catch block that I'm not allowed to alter at the moment as it has nothing to do with the requested code/functionality changes.

Having said that, I'm a bit rusty with exceptions. Kyle, I'm not sure what you meant by
Note that the first string is the exception message,
.

If my catch block only accepts a single parameter, as in: catch(Exception ex), then how is it that passing a string by doing: throw new Exception(string) works?
0
 
LVL 8

Author Comment

by:pzozulka
ID: 40357584
In other words, it seems that the catch method is expecting a parameter of type Exception, but my Throw call sends a parameter of type string. How does this work?
0
 
LVL 11

Assisted Solution

by:louisfr
louisfr earned 100 total points
ID: 40357667
The parameter of the throw statement is an Exception object. See the "new Exception" after the "throw" keyword?
The string is the parameter of the constructor of the Exception object.
0
 
LVL 40

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 200 total points
ID: 40358292
It might be helpful to look at it like this:
Exception myEx = new Exception("Message");
throw myEx;

it's the same thing as:
{
   throw  new    exception ("message")
}

new Exception(string) creates an exception message which is then thrown right away.

Exceptions can have a message, along with an innerexception . . . which might or might not provide more detail.  I was just letting you know there are 2 places to check.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question