जब आप real-world systems बनाते हो—
जैसे GPS Server, Web API, Billing Software, School ERP, E-Commerce Backend,
तो सबसे बड़ा डर यही होता है:
कहीं code run होते समय error आया
और पूरा server क्रैश!
Server crash होना मतलब:
सभी devices disconnect
सभी users को error
data loss
client का गुस्सा 😅
इसीलिए C# में Exception Handling “LIFE-SAVER” होता है।
आज इसे बेहद आसान तरीके + आपके GPS Device Project के Real Examples से सीखते हैं।
Exception = जब code चलते-चलते अचानक कोई अप्रत्याशित error हो जाए।
Real-life examples:
File नहीं मिला
Network timeout
GPS packet format गलत
Divide by zero
Null value
Database connection fail
Exception handling का मतलब है:
Error आए → लेकिन system crash न हो।
try
{
int x = 10 / 0; // error
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Program crash नहीं होगा,
catch block error पकड़ लेगा।
GPS device कभी-कभी खराब packet भेज देता है, जैसे:
,,LAT=xyx,LON=--,..invalid data..
अगर parsing fail हो जाए,
server crash ना हो—
उसे catch करना जरूरी है।
double lat = Convert.ToDouble(parts[3]); // crash!
try
{
double lat = Convert.ToDouble(parts[3]);
}
catch
{
Console.WriteLine("Invalid latitude received!");
}
अब गलत packet →
server safe रहेगा।
हर error के लिए अलग catch बन सकता है।
try
{
var value = Convert.ToInt32(input);
}
catch (FormatException)
{
Console.WriteLine("Invalid number format!");
}
catch (OverflowException)
{
Console.WriteLine("Number too big!");
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}
Cleanup के लिए perfect:
finally
{
Console.WriteLine("Packet processing complete.");
}
Real-life example:
GPS server में हर packet पर clean-up tasks जैसे:
update last processed time
dispose resources
close streams
void ProcessPacket(string packet)
{
try
{
var lat = ParseLatitude(packet);
var lon = ParseLongitude(packet);
UpdateDeviceLocation(lat, lon);
}
catch (Exception ex)
{
LogError("Packet error: " + ex.Message);
}
}
Server कभी crash नहीं होगा—even if packet is corrupted.
GPS location DB में save करते समय भी error आ सकती है:
try
{
db.Save(device);
}
catch (SqlException ex)
{
LogError("DB Error: " + ex.Message);
}
आप खुद exception बना सकते हो:
class InvalidPacketException : Exception
{
public InvalidPacketException(string msg) : base(msg) { }
}
Use:
throw new InvalidPacketException("Packet signature missing!");
बड़े systems में यही तरीका best है।
ASP.NET Core में middleware से global exception handling कर सकते हैं:
app.UseExceptionHandler("/error");
आपके APIs crash नहीं होंगे।
Exception Handling आपके system को देता है:
✔ Stability
✔ No crashes
✔ Safe packet processing
✔ Secure APIs
✔ Clean logging
✔ Better debugging
GPS Servers, Banking, Billing, Schools—
हर production system exception handling पर चलता है।
0 Comments
Thanks for Commenting on our blogs, we will revert back with answer of your query.
EmojiThanks & Regards
Sonu Yadav