Why doesn't Matlab `fopen` throw an exception? - matlab

Why doesn't fopen throw an exception when the filename or path doesn't exist?
in_path = 'pqlcnaf8765mlr9f6lf2;
try
in_file_id = fopen(in_path,'r');
catch
error('Problem with input file.')
end
The in_path doesn't exist. The call returns in_file_id with the value of -1, but no exception is thrown. Does somebody know why?

It's not designed to throw an exception, as the documentation states:
If fopen cannot open the file, it returns -1.
You need to design your code to throw the exception that you want:
in_path = 'pqlcnaf8765mlr9f6lf2;
in_file_id = fopen(in_path,'r');
if in_file_id == -1
error('Problem with input file.')
end
edit
Re: The link in the 1st comment -> shows how to deal with a try catch block. It is throwing an error because of the fread line. You could do the same in your code:
try
in_file_id = fopen(in_path,'r');
fread(in_file_id);
catch
error('Problem with input file.')
end
Having said that I don't think the link is a good example how to deal with a file not existing.

Related

XmlReader and malformed comments

I am using this code to load XML that has the potential for errors (human edited).
$xmlReaderSettings = [System.Xml.XmlReaderSettings]::new()
$xmlReaderSettings.CloseInput = $True
$xmlReaderSettings.IgnoreWhitespace = $True
$xmlReaderSettings.IgnoreComments = $True
try {
$xmlReader = [System.Xml.XmlReader]::Create("$xmlPath\$file", $xmlReaderSettings)
$tempXml = [System.Xml.XmlDocument]::new()
$tempXml.Load($xmlReader)
} catch [System.Management.Automation.ItemNotFoundException] {
Write-PxLog "*_Cannot find '$($file.Name)'"
} catch {
Write-PxLog "*_Malformed XML in '$($file.Name)'"
Write-PxLog "*_$($PSItem.Exception.Message)"
$proceed = $false
} finally {
$xmlReader.Close()
}
This seems to catch all errors except errors related to comments. Specifically, Autodesk uses arguments like --trigger_point system for their uninstalls, and I have that in the XML. If that XML get's commented there is a problem, because a comment can't contain --. Unfortunately, the code above completely misses that error. I can use
if ($tempXml.DocumentElement) {
# continue with validating loaded XML
} else {
# report generic error here
}
I would prefer to provide a more detailed error message, ideally with line numbers. But I would have expected $xmlReaderSettings.IgnoreComments = $True would have solved the issue, as the comments get ignored, and the error is in the comments. If I output the XML again, the comments are missing, but it would seem that IgnoreComments really means IgnoreWellFormedComments, and I have to deal with the issue some other way?
Is there a way to actually ignore malformed comments? And if not, why am I not seeing an exception caught? And is there a better answer than "Something happened and it might be a problem in a comment but I can't tell you where, thanks Microsoft." ?

Why do we put "e" in our catch argument, in Flutter/Dart?

For instance:
try{
Parser p = Parser();
Expression exp = p.parse(expression);
ContextModel cm = ContextModel();
evaluated = exp.evaluate(EvaluationType.REAL, cm);
result = '$evaluated';
}
catch(e)
{
result = "no";
}
I see a lot of flutter related youtube tutorials simply putting "e" as their argument in the catch. Why do we do this? Does e simply mean any type of error?
No there is no special meaning, e is used as a placeholder. You can actually put any letter or allowed symbol like (_), and it will still represent the exception type incoming when error is thrown.
The parameter of catch is the exception object that is being thrown.
It's just the name of exeption, you can call it "exeption" or "e" . In most cases you`re going to see this written as "e" - short for exeption or error.

How do I print a message if a ValueError occurs?

while answers_right < 3:
ran_number_1 = random.randint(10, 99)
ran_number_2 = random.randint(10, 99)
solution = ran_number_1 + ran_number_2
print(f"What is {ran_number_1} + {ran_number_2}?")
user_answer = int(input("Your answer: "))
if user_answer == solution:
answers_right += 1
print(f"Correct. You've gotten {answers_right} correct in a row.")
elif user_answer != solution:
answers_right = 0
print(f"Incorrect. The expected answer is {solution}.")
if answers_right == 3:
print("Congratulations! You've mastered addition.")
I want to add an additional if statement in case someone types string and return a message that says "Invalid Response" instead of the Traceback Error.
Use of Exception handling in python may be solve your Problem and you can also generate your own error class for particular condition.
if x < 3:
raise Exception("Sorry, no numbers below 3")
Use of throw and raise keyword you can generate your own error.
for more referencelink here
The correct way to solve this problem is to look at the error type in your traceback, and use a try/except block. It will say something like TypeError: error stuff here or ValueError: error stuff also here.
The way you do a try/except is to:
try:
some_code()
that_might()
produce_an_error()
except some_error_type:
do_stuff()
except_some_other_error_type:
do_other_stuff()
So, to catch a ValueError and a TypeError, you might do:
try:
buggy_code()
except ValueError:
print("Woah, you did something you shouldn't have")
except TypeError:
print("Woah, you did something ELSE you shouldn't have")
If you then want the traceback, you can add in a lone "raise" statement below the excepts. For example:
try:
buggy_code()
except ValueError:
print("Woah, you did something you shouldn't have")
raise
except TypeError:
print("Woah, you did something ELSE you shouldn't have")
raise
Errors have evolved to be a lot more useful in modern times. They don't break the entire system anymore, and there are ways of handling them. Try/Except blocks like the above give you the tools to have code that only executes when a specific error or set of errors is raised.

Matlab: check if string has a correct file path syntax

I want to check if a string represents a full path of a file, like this:
p = 'C:\my\custom\path.txt'
The file does not exist, so commands like isdir and exist return false to me, but still the format of the string represents a valid path for my operating system, while the following one does not because it has an invalid character for the file name:
p = 'C:\my\custom\:path.txt'
So I'd like to know how to check if a string represents a valid file path without needing that the file actually exists.
You might want to use the regexp function with a regular expression to match Windows paths.
if isempty(regexp(p, '^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$', 'once'))
// This is not a path
end
You can also let Matlab try for you:
if ~isdir(p)
[status, msg] = mkdir(p);
if status
isdir(p)
rmdir(p)
else
error(msg)
end
end
First, you check if the folder exists, if not you try to create it. If you succeed then you delete it, and if not you throw an error.
This is not recommended for checking many strings but has the advantage of being cross-platform.
function bool = isLegalPath(str)
bool = true;
try
java.io.File(str).toPath;
catch
bool = false;
end
end

Error in drool file: input mismatch

I am working on a drool file with the below code:
rule "test rule"
#RuleNumber(1)
#RuleMessage("data mismatch")
when
$myObj : MyObj($localVal1: val1)
$dataMismatch: Boolean() from ($localVal1 == null)
eval $dataMismatch
then
//do something
end
I keep getting the error mismatched input '$dataMismatch' in rule, Parser returned a null Package
Does anyone know where am I going wrong?
Thanks!
Unless you get paid by lines of code written, you should use:
rule "test rule"
#RuleNumber(1)
#RuleMessage("data mismatch")
when
$myObj : MyObj(val1 == null)
then
//do something
end
(Looking into syntax errors cannot be done reliably without knowing the Drools version, which you haven't provided.)