I've the function that uses a password, when I was running the program, the error in the function does not appear in the message box that I put on the catch, how to give an error on the line that give an error?
public void CheckContent(string FileExe, string password)
{
try
{
SevenZipExtractor szip = new SevenZipExtractor(FileExe, password); // <-- error if wrong password
foreach (ArchiveFileInfo file in szip.ArchiveFileData)
{
string NamaFile = file.FileName;
string format = file.Extension;
string[] row;
row = new string[] { NamaFile, format };
DGVDekripsi.Rows.Add(row);
}
}
catch (IOException ex)
{
MessageBox.Show(this, ex.Message, "Proses Cek Isi File Exe", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Probably the type of throwing exception is different than IOException, your catch block will catch only IOException's. Try this:
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Proses Cek Isi File Exe", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
If you write ex.GetType() you will see the type of exception.Then if you wish you can add extra cath block to catch that exception and you can handle it properly.
Are you sure that your exception rise? or it's a general exception, did you trace it?
i think you have a normal exception not IOException
Related
I am trying to catch the Access Denied Exception when trying to upload a file via FTP using FluentFTP
try
{
client = new FtpClient(serverName, userName, password);
client.AutoConnect();
client.RetryAttempts = 3;
client.UploadFile(localPath, serverPath, FtpRemoteExists.Overwrite, false,FtpVerify.Retry);
}
catch (Exception ex)
{
if (ex is FtpException && ex.InnerException?.Message == "Access is denied. ")
{
//Do something here
throw ex;
}
throw;
}
I cannot rely on "Access is denied. " on this string but I don't know how to catch that Exception.
I would recommend that you check the directory before moving on to upload:
if (!client.DirectoryExists(serverPath))
{
//do somthing...
}
you can also try to get the permission of file/directory and catch exception thrown by it:
try
{
...
var ftpListItem = client.GetFilePermissions(pathOnTheServer);
if (ftpListItem.GroupPermissions == FtpPermission.None ||
ftpListItem.OthersPermissions == FtpPermission.None
) //or other permission category..
{
//do something...
return;
}
//do other things..
}
catch (FtpCommandException ex) //get permission failed
{
//handle exception
}
catch(Exception ex)
{
//hendel other exceptions
}
Bounce:
you can use using statement to properly dispose the client after done using it:
using (var client = new FtpClient(serverName, userName, password))
{
//your code...
}
In the try catch block want to get the catch exception code, we know that 404: not found, 400: bad request. In my catch block want to get exception code. How to get exception code in C# catch block.
try
{
await next(context);
}
catch (Exception ex)
{
}
You can just catch the WebException, and then, check the ProtocolError and status code.
}
catch(WebException e) {
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
catch(Exception e)
{
//
}
I'm trying to catch a duplicate key violation. I can see the System.OleDB.OleDBException in the Intellisense pop up, but the inner exception is null. How do I access the Error Code in the System.OleDB.OleDBException?
Greg
try
{
MyData.ConExec(sSQL);
}
catch (Exception ex)
{
OleDbException innerException = ex.InnerException as OleDbException;
if (innerException.ErrorCode == -2147217873)
{
// handle exception here..
}
else
{
throw;
}
}
don't declare an instance of the exception. It will surely return empty if you do.
try
{
MyData.ConExec(sSQL);
}
catch (OleDbException ex)
{
// handle excpetion here...
if (ex.ErrorCode == -2147217873)
{
}
}
catch (Exception e)
{
// if other exception will occur
}
i have a code to restart a service in an event which does other functions too.
I have a try catch in the event for everything within the event like this:
private void btnApply_Click(object sender, EventArgs e)
{
try
{
applyChangesAndCheckRestartService();
}
catch (Exception ex)
{
MessageBox.Show("Error loading page.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void applyChangesAndCheckRestartService()
{
string svrPortNo = CommonCodeClass.getTagValue(CommonCodeClass.xml_SvrPortNoTag, CommonCodeClass.configLocation + CommonCodeClass.configXML);
if (!ApplyChangesForSettings())
{
return;
}
if (svrPortNo != tbSvrPortNo.Text)
{
CommonCodeClass.CheckToRestartService();
}
}
Now if there is an error during ApplyChangesForSettings() i will get an error popup "Error loading page".
If there is an error in CheckToRestartService() i will get the same error because of the try catch.
Is there a better way to handle this.
Like i dont mind the error loading page for ApplyChangesForSettings() but for CheckToRestartService() i would like to see an error like "unable to restart service".
Any suggestions are appreciated.
Thanks
internal static void CheckToRestartService()
{
DialogResult result = MessageBox.Show(CommonCodeClass.resartServiceMessage, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
CommonCodeClass.RestartService(CommonCodeClass.serviceName, 60000);
}
}
Do they throw different exceptions? If they do you could use exception filtering:
private void btnApply_Click(object sender, EventArgs e)
{
try
{
applyChangesAndCheckRestartService();
}
// catch service start exceptions
catch (InvalidOperationException ioex)
{
// display message that couldn't start service
}
// catch rest
catch (Exception ex)
{
MessageBox.Show("Error loading page.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
UPDATE this is assuming you're calling something like ServiceController.Start() which throws InvalidOperationException on failure, you could easily throw this yourself on your own error condition or create your own custom exception.
if (/* service didn't start */)
{
throw new InvalidOperationException("Could not start service.");
}
You either need to
catch the exception in applyChangesAndCheckRestartService
or you could pass an enum by ref f.e. called RestartStatus
enum RestartStatus{success, unableToRestart, unableToApplySettings};
RestartStatus status = RestartStatus.success;
applyChangesAndCheckRestartService(status);
if(status != RestartStatus.success) //....
private void applyChangesAndCheckRestartService(out RestartStatus status)
{
// set the status variable accordingly
}
A third way is to use custom exceptions that you can catch separately.
Well maybe you just need to wrap the different functions with separate try/catch blocks:
try {
if (!ApplyChangesForSettings())
return;
}
catch (Exception ex) {
MessageBox.Show("Error loading page.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (svrPortNo != tbSvrPortNo.Text) {
try {
CommonCodeClass.CheckToRestartService();
}
catch (Exception ex) {
MessageBox.Show("Unable to restart services.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Or, you could consider catching different types of exceptions, if they threw different types:
string errmsg = string.empty;
try {
DoSomething();
}
catch (FooException) {
errmsg = "There was a Foo error";
}
catch (WidgetException) {
errmsg = "There was a problem with a Widget";
}
catch (Exception ex) {
errmsg = "General problem: " + ex.Message;
}
if (!string.IsNullOrEmpty(errmsg))
MessageBox.Show(errmsg);
See also:
Exception Handling
The fastest way to handle this situation is throwing an exception when someone of your internal methods fails and catch the message in the btnApply_Click.
MessageBox.Show(ex.Message, "Error", .....);
The rightest way is to create your own exception type and inside the methods, if there is a fail condition throw your own exception. For example create a class like this
public class RestartServiceException : Exception
{
public RestartServiceException(string message)
: base(message)
{
}
// You could also write other constructors with different parameters and use internal logic
// to process your error message
}
and then, use an instance of that class when the fail condition arise inside your CheckToRestartService method
if(fail == true)
throw new RestartServiceException("The service could not be started because .....");
Below is some of my error logging code. When an exception happens inside my app, I log it to a database. If that database is down or when there's some other problem, I try to log it in an event viewer.
What happens if that event viewer write fails for some reason, too? How do I give up or swallow this new exception?
void SaveLog(string accountId, Exception ex, Category category, Priority priority)
{
try
{
using (var connection = new SqlConnection(…))
{
connection.Open();
command.ExecuteNonQuery();
}
}
catch (Exception exception)
{
// exception while logging!
using (var eventLog = new EventLog { Source = "tis" })
{
eventLog.WriteEntry(
exception.Message + Environment.NewLine +
exception.StackTrace,
EventLogEntryType.Error);
}
}
}
try {
// ...
}
catch (Exception exception) {
try {
// Attempt to write to event log.
}
catch {
}
}