How to handle failed Matlab constructor? -
the matlab docs give example of class closes file if object deleted. i'm trying similar serial port object, if constructor fails valid handle object, delete method throw error. so question how make this: classdef filewriter < handle properties (access = private) fileid end methods function obj = filewriter(filename) obj.fileid = fopen(filename,'a'); % if fails... end function writetofile(obj,text_str) fprintf(obj.fileid,'%s\n',text_str); end function delete(obj) fclose(obj.fileid); % fail end end end ...where constructor may fail? in constructor should check failure. in case comparing fileid -1 , calling error . in delete method check fileid against -1 well, , not perform fclose , if -1 , perform cleanly.