By definition, one cannot act on a given Document's Database, without a valid Document (or opening as a side database). Thus, to use code logic to test for:
// ...
if (<MdiActiveDocument> == null)
Return;
// <-- do something useful
// ...
Anytime MdiActiveDocument is not null, you will be able to query the Document's Database. Anytime it is null, there is no Document, nor any Database to query, precluding an Exception from being raised by your code.
Also, you may want to familiarize yourself with the new non-DWG Documents as well.
Cheers