473,397 Members | 1,949 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

.NET Exception Handling

I have never understood how to throw exceptions properly. If my method is supposed to return an array, when I try to throw the error "ex.Message.ToString() it won't compile. The method is calling for an array but the error throws string. I know this is really stupid of me, but can someone help me with this very basic concept....PLEASE!!!!!

Thanks so much!

Spartacus
Nov 17 '07 #1
4 1412
Shashi Sadasivan
1,435 Expert 1GB
Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.    //your code goes here
  4. catch(Exception ex)
  5. {
  6.    MessageBox.Show(ex.Message);
  7. }
thats a usual try catch block.
Your array code (which has the array in it) should be sitting in the try block.
and if that fails, it enters the catch block.
If an exception occours, its details are contained in the Exception object representend by "ex" above.
The object "ex" does not require/ask for an array in the ex.Message.toString() method.
if you debug this code, and if it enters the catch statement, hover your mouse on ex to see its methods and properties and what they contain.

cheers
Nov 18 '07 #2
Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.    //your code goes here
  4. catch(Exception ex)
  5. {
  6.    MessageBox.Show(ex.Message);
  7. }
thats a usual try catch block.
Your array code (which has the array in it) should be sitting in the try block.
and if that fails, it enters the catch block.
If an exception occours, its details are contained in the Exception object representend by "ex" above.
The object "ex" does not require/ask for an array in the ex.Message.toString() method.
if you debug this code, and if it enters the catch statement, hover your mouse on ex to see its methods and properties and what they contain.

cheers
Thanks so much for the response, I left out something, this is for a web service and and I am filling a dataset which then is used to populate an array. I want to check for sql errors. Below id the method:

Expand|Select|Wrap|Line Numbers
  1.    [WebMethod(Description = "Returns weekly revenue levels by day!")]
  2.     public dataForWeekVO[] DataForWeek(string dteWEDate, string strType)
  3.     {
  4.         DateTime shpDate = Convert.ToDateTime(dteWEDate);
  5.  
  6.         cn = new SqlConnection(sqlCSConnectionString);
  7.         System.Data.SqlClient.SqlCommand cmd = new SqlCommand("WE_DataForWeek_S", cn);
  8.         cmd.CommandType = CommandType.StoredProcedure;
  9.         cmd.Parameters.AddWithValue("@wedate", shpDate);
  10.         cmd.Parameters.AddWithValue("@type", strType);
  11.  
  12.         cn.Open();
  13.  
  14.         try
  15.         {
  16.  
  17.             SqlDataAdapter da = new SqlDataAdapter(cmd);
  18.             System.Data.DataSet ds = new System.Data.DataSet();
  19.             da.Fill(ds, "DataForWeek");
  20.  
  21.             int c = (ds.Tables["WeeklyData"].Rows.Count);
  22.             dataForWeekVO[] dataForWeek = new dataForWeekVO[c];
  23.  
  24.             for (int i = 0; i < (ds.Tables["DataForWeek"].Rows.Count); i = i + 1)
  25.             {
  26.                DataRow aRow = ds.Tables[0].Rows[i];
  27.                dataForWeek[i] = new dataForWeekVO();
  28.                dataForWeek[i].date = Convert.ToDateTime(aRow["Date"].ToString());
  29.                dataForWeek[i].ddd = Convert.ToDecimal(aRow["DDD"].ToString());
  30.                dataForWeek[i].dtrl = Convert.ToDecimal(aRow["DTRL"].ToString());
  31.                dataForWeek[i].cnsd = Convert.ToDecimal(aRow["CNSD"].ToString());
  32.                dataForWeek[i].usps = Convert.ToDecimal(aRow["USPS"].ToString());
  33.               dataForWeek[i].smtp = Convert.ToDecimal(aRow["SMTP"].ToString());
  34.                 dataForWeek[i].lsca = Convert.ToDecimal(aRow["LSCA"].ToString());
  35.                 dataForWeek[i].fxce = Convert.ToDecimal(aRow["FXCE"].ToString());
  36.                 dataForWeek[i].fxh3 = Convert.ToDecimal(aRow["FXH3"].ToString());
  37.                 dataForWeek[i].total = Convert.ToDecimal(aRow["Total"].ToString());
  38.  
  39.             }
  40.  
  41.             return dataForWeek;
  42.  
  43.         }
  44.  
  45.         catch (System.Data.SqlClient.SqlException ex)
  46.         {
  47.             throw ex.Message.ToString();
  48.  
  49.  
  50.         finally
  51.         {
  52.             if (cn.State == ConnectionState.Open)
  53.             {
  54.                 cn.Close();
  55.             }
  56.         }
  57.  
  58.     }
The above code won't compile. The compile error is "not all code paths return a value". Also since it's a web service should I be using HTTPException or SOAPException?

Thanks again for you help!

spatacus
Nov 18 '07 #3
Shashi Sadasivan
1,435 Expert 1GB
Expand|Select|Wrap|Line Numbers
  1. catch (System.Data.SqlClient.SqlException ex)
  2.         {
  3.             throw ex.Message.ToString();
  4.  
  5.  
  6.         finally
  7.         {
  8.             if (cn.State == ConnectionState.Open)
  9.             {
  10.                 cn.Close();
  11.             }
  12.         }
the catch statment dosent have an end to it.

why the compiler refuses to compile it is because it senses more than one path and checks if it goes through any path, there is something that is returned.

If you put a return statement after the finally block it will work.
Nov 18 '07 #4
I have this function which will accept a time as string

Public Shared Function SpecTime(ByVal timeStr As String) As String
Dim dt As DateTime
If String.IsNullOrEmpty(timeStr) Then
Return ""
Else
Try
dt = DateTime.Parse("1/8/1985 " + timeStr)
Catch ex As Exception

End Try
Return dt.ToString("h:mm tt")
End If
End Function

when i input an invalid time str eg. "1a", how do i know the unique code for that specific exception? how will it know that "12 a" is invalid or "12;00" is invalid???

my point here is that i need to know the unique exception code (if there is any) so i could handle the different exceptions accordingly.

tnx!
Feb 5 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: adi | last post by:
Dear all, This is more like a theoretical or conceptual question: which is better, using exception or return code for a .NET component? I had created a COM object (using VB6), which uses...
6
by: Daniel Wilson | last post by:
I am having exception-handling and stability problems with .NET. I will have a block of managed code inside try...catch and will still get a generic ..NET exception box that will tell me which...
7
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
3
by: Master of C++ | last post by:
Hi, I am an absolute newbie to Exception Handling, and I am trying to retrofit exception handling to a LOT of C++ code that I've written earlier. I am just looking for a bare-bones, low-tech...
2
by: tom | last post by:
Hi, I am developing a WinForm application and I am looking for a guide on where to place Exception Handling. My application is designed into three tiers UI, Business Objects, and Data Access...
9
by: C# Learner | last post by:
Some time ago, I remember reading a discussion about the strengths and weaknesses of exception handling. One of the weaknesses that was put forward was that exception handling is inefficient (in...
44
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level...
4
by: Ele | last post by:
When Exception handling disabled compiler still spits out "C++ exception handler used." Why is that? Why does it ask for "Specify /EHsc"? Thanks! c:\Program Files\Microsoft Visual Studio...
41
by: Zytan | last post by:
Ok something simple like int.Parse(string) can throw these exceptions: ArgumentNullException, FormatException, OverflowException I don't want my program to just crash on an exception, so I must...
1
by: George2 | last post by:
Hello everyone, Such code segment is used to check whether function call or exception- handling mechanism runs out of memory first (written by Bjarne), void perverted() { try{
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.