Can't catch NullReferenceException [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
First post here, so sorry if I've got some of the niceties wrong. I'm trying to catch an exception where the user enters an invalid (non-existent) employee. I've tried many different variations, but the error is never raised. Instead the code just terminates, in this case it will drop out after the following lines:
MyPostSalary = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
Can anyone see what I'm doing wrong?
Complete code:
Console.Write("Employee ID: ");
myEID = Console.ReadLine();
try
{
Console.Write("Post ID: ");
myPID = Console.ReadLine();
if ((myEmployees[myEID] is MonthlyPaidEmployee) || (myEmployees[myEID] isWeeklyPaidEmployee))
{
Console.Write("Post Name: ");
MyPostName = Console.ReadLine();
Console.Write("Post Start Date: ");
MyPostStartDate = Convert.ToDateTime(Console.ReadLine());
Console.Write("Post End Date: ");
MyPostEndDate = Convert.ToDateTime(Console.ReadLine());
Console.Write("Post Salary: ");
MyPostSalary = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
myPost = new Post(myPID, MyPostName, MyPostStartDate, MyPostEndDate, MyPostSalary);
if (myEmployees[myEID] is MonthlyPaidEmployee)
{
myMonthlyEmp = (MonthlyPaidEmployee)myEmployees[myEID];
myMonthlyEmp.PostHistory.Add(myPID, myPost);
}
if (myEmployees[myEID] is WeeklyPaidEmployee)
{
myWeeklyEmp = (WeeklyPaidEmployee)myEmployees[myEID];
myWeeklyEmp.WeeklyPaidEmployeePostHistory.Add(myPID, myPost);
}
}
}
catch (NullReferenceException ex)
{
Console.WriteLine("Employee ID does not exist.");
Console.WriteLine(ex.Message);
Console.WriteLine();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}

Are you in debug on Visual Studio (or your IDE)?
If yes, it maybe you are catching the exception but the IDE is set to show a warning message when the exception raises...
Try to run your application outside the IDE, if it works you can disable warning when NullReferenceExceptions raise , but it is quite dangerous. To do this look for "Exceptions settings" in Visual Studio (or something like this, I'm not sure because I use the italian version).

You are only catching NullReferenceException exception, but as you see in the method description of Convert.ToDouble(), it throws an InvalidCastException.
So try catch (InvalidCastException ex) instead.
Also pay attention to FormatException and OverflowException.

It's fairly clear that you are not getting a NullReferenceException. I recommend that you try the following:
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
Find out which exception you're receiving, and either catch that specific exception, or else prevent it from occurring in the first place.
You should never catch NullReferenceException.

Aren't you getting a double conversion exception? You should probably use Double.TryConvert rather than Convert.

It looks like the entered text can't be converted to a double.
Try catching an InvalidCastException.

Related

Is there a way to return a value from a try-catch block into a preexisting variable outside of the block itself?

I feel like this may be somewhat of a dumb question, but I've tried everything I currently know to do as a beginner of C# on this. Is there any way I can return a value into one I've already set to use elsewhere? Or am I just over-complicating this whole thing? Every time I try to set the already existing variable with one inside the curly brackets I get an error. Code I used below.
static double GetAmount()
{
double amount;
try
{
Console.WriteLine("Enter in the amount for the transaction: ");
double amount1 = Convert.ToDouble(Console.ReadLine());
return amount1;
}
catch (Exception ex)
{
bool f = true;
Console.WriteLine(ex.Message);
while (f == true)
try
{
Console.WriteLine("Enter the total in a proper format, no letters or spaces please. ");
double amount1 = Convert.ToDouble(Console.ReadLine());
f = false;
return amount1;
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
Console.WriteLine("Please try again.");
}
}
finally
{
return amount;
}
return amount;
}
You get two compilations errors and a warning. To understand them you must know that the finally-block is always executed before returning from the try- or catch-block. I.e., return amount1; would execute the statement in finally-block return amount;. But only one return-statement can be executed. Therefore, you get the message:
CS0157 Control cannot leave the body of a finally clause
and
CS0165 Use of unassigned local variable 'amount'
because the variable is declared but is not assigned a value yet when return is called.
Also, you get the warning
CS0162 Unreachable code detected
on the last code line, because the method will either be left by one of the previous return-statements or stay in the while-loop forever. Therefore, this last return statement can never be executed.
The bool flag f is redundant. There is no point in setting it to true before the return statement since the method is exited at the return-statement. This terminates the while-loop at the same time. If you want to exit the loop without returning, you can call break;.
Simplified version using try-catch:
static double GetAmount()
{
Console.Write("Enter in the amount for the transaction: ");
while (true) {
try {
double amount = Convert.ToDouble(Console.ReadLine());
return amount;
} catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.Write("Enter the total in a proper format, no letters or spaces please: ");
}
}
}
The statement while (true) introduces an endless loop. Endless unless it is left by return, break or an unhandled exception (or the frowned upon goto command).
A better alternative is to use the TryParse method that does not throw an exception
static double GetAmount()
{
Console.Write("Enter the amount for the transaction: ");
while (true) {
if (Double.TryParse(Console.ReadLine(), out double amount)) {
return amount;
}
Console.Write("Enter the total in a proper format: ");
}
}
This version has the same functionality as yours, is safe, is 3 times smaller and is much easier to read.
See also: try-finally (C# Reference)
static double GetAmount()
{
double amount = 0;
try
{
Console.WriteLine("Enter in the amount for the transaction: ");
amount = Convert.ToDouble(Console.ReadLine());
}
catch (Exception ex)
{
bool f = true;
Console.WriteLine(ex.Message);
while (f)
try
{
Console.WriteLine("Enter the total in a proper format, no letters or spaces please. ");
amount = Convert.ToDouble(Console.ReadLine());
f = false;
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
Console.WriteLine("Please try again.");
}
}
return amount;
}

Make the error shorter

I made a program in c#(I don't put here the code because there are lot of classes),and I made Exceptions to throw the mistakes,and when a mistake occurs this is what appears in the console:
System.Exception: Student whit id:1 already exists! at
StudentManagment.Service.AbstractService`4.Add(E entity) in
C:\Users\Robbi\source\repos\StudentManagment\StudentManagment\Service\AbstractService.cs:line
34 at StudentManagment.Domain.Program.Main(String[] args) in
C:\Users\Robbi\source\repos\StudentManagment\StudentManagment\Program.cs:line
23
And my question is, How can I make that in the console to appear just
Student whit id:1 already exists!
Catch the exception into a variable and output the exception.Message only. You are seeing a stack trace - ie all the methods that are in execution at the point of error. StackTraces are useful for debugging purposes, but not so great for displaying information to a user.
i.e
try
{
//do error here
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
This is a very beginner issue
While you show no code, heres some semi fake code to answer the question
try
{
do_it();
}
catch (Exception myEx) // you can do different things with different exception types
{
Console.WriteLine("Error: "+myEx.Message);
}
You have to use
ex.Message
where ex is your exceptption, something like
try
{
...
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
Of course, edit this minimal snippet code to satisfy your needs

How to handle exception in catch block?

I am trying to get the ideal way to handle exception. I googled & read that I should put try catch in the catch block as well to handle but what if any exception occurs in the nested block itself.
try
{
int a = 10;
int b = 0;
int c = a / b;
Console.WriteLine(c);
Console.ReadKey();
}
catch (Exception ex)
{
int a = 10; int b = 0;
int c = a / b;
Console.WriteLine(ex.Message.ToString());
Console.ReadKey();
}
finally
{
Console.WriteLine("Some Exception");
}
On googling I read that it should be decorated as below:
If exception occurs in Catch block itself then how to handle it in C#?
If exception occurs in Catch block itself then how to handle it in C#?
What happens if an exception occurs in Catch block in C#. Also what would be the caller result in that case
try
{
int a = 10;
int b = 0;
int c = a / b;
Console.WriteLine(c);
Console.ReadKey();
}
catch (Exception ex)
{
try
{
}
catch(Exception innerEx)
{
// What if exception here also occurs.
}
}
finally
{
Console.WriteLine("Some Exception");
}
If I do this way, then it will stuck in an infinite try-catch block.
I think there would be some better or the right way to handle this scenario.
I think there would be some better or the right way to handle this scenario.
No snark intended in this but simply, don't allow an exception to happen in the first place.
A try...catch is a language construct that ensures you handle an edge case or error you didn't mitigate and design for in the first place, hence why it's exceptional code.
In your code, you're simply throwing an error because of a division by 0, but in the real-world, you want to handle that and alert the user (or developer, or server, or whatever), and then handle the actual exceptional code, example:
static void PrintError()
{
Console.WriteLine("You must enter a valid number between {0} and {1}, excluding 0", int.MaxValue, int.MinValue);
}
static void Main(string[] args)
{
try {
int a = 10;
int b = 0;
PrintError(); // Tell user to enter valid numbers
while (b == 0) {
string user_input = Console.ReadLine();
if (int.TryParse(user_input, out b)) { // is it an actual number?
if (b == 0) { // no 0's remember user!??
PrintError();
} else {
// ok, everything checks out, so do what the system can actually handle without throwing an error
Console.WriteLine("a/b = {0}", (a / b));
}
} else {
PrintError();
}
}
} catch (Exception ex) {
Console.WriteLine("Something exceptional happened: {0}", ex);
}
}
This example could be simplified further, but it demonstrates there isn't an exception that could actually occur except something that is actually exceptional (i.e. out of memory error or some other system error).
In the event of larger code bases with multiple classes, the exception handler and finalizer would be where you could clean up resources acquired in other areas of the code, like closing a socket or file handle to ensure data is not lost.
In the event an error happens in the exception handler (something that can and does happen), you need to be aware of that and know what might happen in that case.
In the event of a C# application utilizing the .NET framework, an exception thrown within an exception will just cause the application to crash with the inner exception stack trace (versus the "outer" exception that's probably more relevant to the actual exception) if not handled.
There's plenty of "wrong" ways to handle exceptions (like not handling them at all), but there's not really a "right" way given the variable nature of exceptions.
Hope that can help.
First of all you need to know what does try,catch and finally works lets start:
Try: In this block we can write code which have the possibilities to throw some error (Better practice is to write code part in it.)
Catch: It is responsible to show error and what to do if error arises(Like in your code 10/0 throws error which can be handled in this section.)
Finally: Code written in this part will execute any how weather any error comes in or not.
Now for your query it would be better that you can use If...else in finally and code put in that part would be kept in try catch block.
For example:
bool flagCatch=false;
try
{
int a = 10;
int b = 0;
int c = a / b;
Console.WriteLine(c);
Console.ReadKey();
}
catch (Exception ex)
{
//Error handling
flagCatch=true;
Console.WriteLine(ex.Message.ToString());
Console.ReadKey();
}
finally
{
try
{
if(flagCatch)
{
//Code
}
else
{
//Code when error not comes
}
}
catch(Exception err)
{
//Error handling
}
}
I would go with the comment of Tieson T. . From my point of view it is an design issue.
I could also build an example with if statements -> if that goes wrong, I perform failure handling -> if the failure handling goes wrong, I perform failure handling, If the failure handling goes wrong ....
To make the code more readable, you can try to "hide" the try-catch blocks in method like:
static void PerformInTryCatch<T, TException>(Action<T> action, T obj) where TException : Exception
{
try
{
action(obj);
}
catch (TException exception)
{
// Perform some logging
}
}
Hope that helps.

Try Catch ~ How to Display Something Different?

I have a really simple question (I'm new to c# visual studios) about the try catch method:
try
{
double seven = 7
MessageBox.Show("You Picked 7!");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I tried replacing the MessageBox.Show(ex.Message); with MessageBox.Show("Please enter a number."); but it won't work.
How should I approach this? There is the error line under the ("Please enter a number.").
Thanks in advance!
You're missing a semi-colon after declaring 'seven'
Below sample works for me.
try
{
double seven = 7;
MessageBox.Show("You Picked 7!");
}
catch(Exception ex)
{
MessageBox.Show("Please enter a number.");
}
Just a tip to if you plan on not using the exception then it's recommended you don't specify an exception as a parameter to catch. See Using catch without arguments
try
{
double seven = 7;
MessageBox.Show("You Picked 7!");
}
catch
{
MessageBox.Show("Please enter a number.");
}

why doesnt it write to file in exception

still giving problem
I have the following code. As long as I am in try { } it writes fine. But when there is an error, it doesn't write to log file. Not sure why
private static void jk(string kName, string path)
{
Job job;
try
{
// run some functions here and then write to the file
StreamWriter LJ = new StreamWriter("C:\\Lob.txt");
LJ.WriteLine("XXXXXXXXXXXX");
LJ.Close();
}
catch (InvalidException)
{
StreamWriter LJ = new StreamWriter("C:\\Lob.txt");
LJ.WriteLine("YYYYYYYYYYYYYYYY");
LJ.Close();
Console.WriteLine("Error: ");
return;
}
}
Because the only thing in your try is writing to the stream... and that's the same thing you try to do in the cacth. Why would that work?
The catch block executes only when the try block throws the exception (which appears to be a typo in the original post).
If the try succeeds, the catch is never executed.
If the try fails, it's because of a problem that must have occurred in writing to the log. When the catch executes, that problem most likely still exists, so the log within the catch will fail also.
Well, I don't know what type LJ is, and I certainly have never heard of a IncalidException. I am assuming that you just typed the code into the editor incorrectly. You should really just paste it in to avoid those types of errors.
Anyway, there are a few options:
LJ.WriteLine is not throwing an exception.
LJ.WriteLine is throwing an exception, but not of the same type you are catching (i.e., see if it works when you just catch { }).
The second call to LJ.WriteLine is also throwing an exception and you are catching (and perhaps swallowing) it further up the stack.
With your comment:
try fails because of some other problems but I am trying to log it
into the file
I assume that the exception is not thrown by LJ.WriteLine("XXXXXXXXXXXX");
If that's the case, you might just need to flush the StreamWriter. Try declaring LJ in a using block like this:
using (StreamWriter LJ = new StreamWriter("C:\\Lob.txt"))
{
LJ.WriteLine("XXXXXXXXXXXX");
try
{
...
LJ.WriteLine("XXXXXXXXXXXX");
}
catch (InvalidException)
{
LJ.WriteLine("YYYYYYYYYYYYYYYY");
Console.WriteLine("Error: ");
return;
}
}
Are you able to compile this code?
There are two things I see incorrect with the above.
It should be InvalidException not IncalidException
try
{
LJ.WriteLine("XXXXXXXXXXXX");
}
catch (InvalidException e)
{
LJ.WriteLine("YYYYYYYYYYYYYYYY");
Console.WriteLine("Error: {0}", e.Message);
return;
}

Categories

Resources