我有一个构造函数
public Track(string path)
{
if (!File.Exists(path))
throw new FileNotFoundException("File not found", path);
if (!IsAudioFile(path))
throw new Exception("Illegal Audio Format");
_path = path;
_id = Guid.NewGuid();
_rate = 0;
_length = GetTrackLength(path);
TagLib.File file = TagLib.File.Create(path);
if (!file.Tag.IsEmpty)
{
try
{
_artist = file.Tag.Artists[0];
}
catch (Exception e)
{
_artist = "";
}
_title = file.Tag.Title;
try
{
_genre = file.Tag.Genres[0].ToGenre();
}
catch (Exception e)
{
_genre = Genre.NoGenre;
}
}
else
{
_artist = "Unknown";
_title = "Unknown";
_genre = Genre.NoGenre;
}
}
我应该抛出异常还是应该选择另一种创建对象的方式?
例如:
跟踪轨道=新轨道(路径);
track = Track.GetInstance();
答案 0 :(得分:1)
您的代码正确且图案精美。
然而,you shouldn't throw the base Exception
class
相反,您应该抛出ArgumentException
,InvalidDataException
或InvalidOperationException
。
您还shouldn't catch the base Exception
class
相反,您应该捕获ToGenre
方法可以抛出的任何异常。
答案 1 :(得分:0)
(通常)没有理由让静态方法返回实例,除非您正在执行单例模式或需要重新使用现有对象而不是创建新实例。
在构造函数中抛出异常很好,通常是正确的处理方式。
答案 2 :(得分:0)
代码很酷。
我所能提供的建议不是使用泛型异常,而是抛出并捕获更具体的上下文。随意使用ArgumentException。
另外,仅适用于checkstyle:
如果你想在if {}块中添加代码,那么总是使用花括号{}是一个好习惯,你可以忘记放括号。虽然这里没有必要。
答案 3 :(得分:0)
我会做一些小修改,如下所示,以避免不必要的异常处理,并在参数检查中抛出一个更加特殊的异常。就投掷构造函数而言,这很好,因为它实际上只是特殊类型的方法。
关于创建新Track
的反馈:您可以在某种管理器(例如TagManager)中放置GetTrack()
方法,如果您认为新建Track
个对象是您的API应该处理的东西,而不是给消费者负责。
public Track(string path)
{
if (!File.Exists(path))
throw new FileNotFoundException("File not found", path);
if (!IsAudioFile(path))
throw new InvalidOperationException("Illegal Audio Format");
_path = path;
_id = Guid.NewGuid();
_rate = 0;
_length = GetTrackLength(path);
TagLib.File file = TagLib.File.Create(path);
if (!file.Tag.IsEmpty)
{
_title = file.Tag.Title;
if (file.Tag.Artists != null && file.Tag.Artists.Count > 0)
_artist = file.Tag.Artists[0];
else
_artist = "";
if (file.Tag.Genres != null && file.Tag.Genres.Count > 0)
_genre = file.Tag.Genres[0].ToGenre();
else
_genre = Genre.NoGenre;
}
else
{
_artist = "Unknown";
_title = "Unknown";
_genre = Genre.NoGenre;
}
}