Bug 1344711 - hand cleanup of remaining useless try blocks around get*Pref calls identified by eslint, r=jaws.
authorFlorian Quèze <florian@queze.net>
Tue, 07 Mar 2017 15:29:48 +0100
changeset 494673 340e7f8a7229786fc8808d4a78983338997f81f3
parent 494672 9c92165fef205c73e6ed11dcdd3f70c435ad3853
child 494674 9c25bdd4968c538c037f53d8a8ad23e7ab67b098
child 494678 4e6fc030c70b70b13f0bd59dd43443bacbc43b21
push id48086
push userbsmedberg@mozilla.com
push dateTue, 07 Mar 2017 16:12:47 +0000
reviewersjaws
bugs1344711
milestone55.0a1
Bug 1344711 - hand cleanup of remaining useless try blocks around get*Pref calls identified by eslint, r=jaws.
accessible/tests/mochitest/jsat/output.js
b2g/chrome/content/devtools/adb.js
b2g/chrome/content/settings.js
b2g/chrome/content/shell.js
b2g/components/AboutServiceWorkers.jsm
b2g/components/Bootstraper.jsm
b2g/components/SignInToWebsite.jsm
browser/base/content/aboutaccounts/aboutaccounts.js
browser/base/content/browser.js
browser/components/customizableui/CustomizeMode.jsm
browser/components/uitour/UITour.jsm
browser/modules/SocialService.jsm
devtools/shared/touch/simulator-core.js
mobile/android/components/DirectoryProvider.js
security/sandbox/test/browser_content_sandbox_fs.js
security/sandbox/test/browser_content_sandbox_syscalls.js
toolkit/components/asyncshutdown/AsyncShutdown.jsm
toolkit/components/places/PlacesCategoriesStarter.js
toolkit/components/places/UnifiedComplete.js
toolkit/components/places/nsPlacesExpiration.js
toolkit/components/places/tests/unit/test_000_frecency.js
toolkit/components/urlformatter/tests/unit/test_urlformatter.js
toolkit/content/contentAreaUtils.js
toolkit/content/widgets/scrollbox.xml
toolkit/modules/Troubleshoot.jsm
toolkit/modules/UpdateUtils.jsm
toolkit/mozapps/extensions/AddonManager.jsm
toolkit/mozapps/extensions/LightweightThemeManager.jsm
toolkit/mozapps/extensions/content/extensions.js
toolkit/mozapps/extensions/nsBlocklistService.js
toolkit/mozapps/extensions/test/xpcshell/test_pref_properties.js
--- a/accessible/tests/mochitest/jsat/output.js
+++ b/accessible/tests/mochitest/jsat/output.js
@@ -55,16 +55,17 @@ function testContextOutput(expected, aAc
 function testObjectOutput(aAccOrElmOrID, aGenerator) {
   var accessible = getAccessible(aAccOrElmOrID);
   if (!accessible.name || !accessible.name.trim()) {
     return;
   }
   var context = new PivotContext(accessible);
   var output = aGenerator.genForObject(accessible, context);
   var outputOrder;
+  // eslint-disable-next-line mozilla/use-default-preference-values
   try {
     outputOrder = SpecialPowers.getIntPref(PREF_UTTERANCE_ORDER);
   } catch (ex) {
     // PREF_UTTERANCE_ORDER not set.
     outputOrder = 0;
   }
   var expectedNameIndex = outputOrder === 0 ? output.length - 1 : 0;
   var nameIndex = output.indexOf(accessible.name);
--- a/b2g/chrome/content/devtools/adb.js
+++ b/b2g/chrome/content/devtools/adb.js
@@ -41,16 +41,17 @@ var AdbController = {
     this.updateState();
   },
 
   startDisableAdbTimer: function() {
     if (this.disableAdbTimer) {
       this.disableAdbTimer.cancel();
     } else {
       this.disableAdbTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+      // eslint-disable-next-line mozilla/use-default-preference-values
       try {
         this.disableAdbTimeoutHours =
           Services.prefs.getIntPref("b2g.adb.timeout-hours");
       } catch (e) {
         // This happens if the pref doesn't exist, in which case
         // disableAdbTimeoutHours will still be set to the default.
       }
     }
--- a/b2g/chrome/content/settings.js
+++ b/b2g/chrome/content/settings.js
@@ -422,22 +422,18 @@ setUpdateTrackingId();
   let geckoPrefName = 'toolkit.telemetry.enabled';
   SettingsListener.observe(gaiaSettingName, null, function(value) {
     if (value !== null) {
       // Gaia setting has been set; update Gecko pref to that.
       Services.prefs.setBoolPref(geckoPrefName, value);
       return;
     }
     // Gaia setting has not been set; set the gaia setting to default.
-    let prefValue = AppConstants.MOZ_TELEMETRY_ON_BY_DEFAULT;
-    try {
-      prefValue = Services.prefs.getBoolPref(geckoPrefName);
-    } catch (e) {
-      // Pref not set; use default value.
-    }
+    let prefValue = Services.prefs.getBoolPref(geckoPrefName,
+                                               AppConstants.MOZ_TELEMETRY_ON_BY_DEFAULT);
     let setting = {};
     setting[gaiaSettingName] = prefValue;
     window.navigator.mozSettings.createLock().set(setting);
   });
 })();
 
 // =================== Low-precision buffer ======================
 (function setupLowPrecisionSettings() {
--- a/b2g/chrome/content/shell.js
+++ b/b2g/chrome/content/shell.js
@@ -251,25 +251,21 @@ var shell = {
     SafeMode.check(window).then(() => {
       let startManifestURL =
         Cc['@mozilla.org/commandlinehandler/general-startup;1?type=b2gbootstrap']
           .getService(Ci.nsISupports).wrappedJSObject.startManifestURL;
 
       // If --start-manifest hasn't been specified, we re-use the latest specified manifest.
       // If it's the first launch, we will fallback to b2g.default.start_manifest_url
       if (AppConstants.MOZ_GRAPHENE && !startManifestURL) {
-        try {
-          startManifestURL = Services.prefs.getCharPref("b2g.system_manifest_url");
-        } catch(e) {}
+        startManifestURL = Services.prefs.getCharPref("b2g.system_manifest_url", "");
       }
 
       if (!startManifestURL) {
-        try {
-          startManifestURL = Services.prefs.getCharPref("b2g.default.start_manifest_url");
-        } catch(e) {}
+        startManifestURL = Services.prefs.getCharPref("b2g.default.start_manifest_url", "");
       }
 
       if (startManifestURL) {
         Cu.import('resource://gre/modules/Bootstraper.jsm');
 
         if (AppConstants.MOZ_GRAPHENE && Bootstraper.isInstallRequired(startManifestURL)) {
           // Installing the app my take some time. We don't want to keep the
           // native window hidden.
--- a/b2g/components/AboutServiceWorkers.jsm
+++ b/b2g/components/AboutServiceWorkers.jsm
@@ -42,20 +42,17 @@ function serializeServiceWorkerInfo(aSer
 }
 
 
 this.AboutServiceWorkers = {
   get enabled() {
     if (this._enabled) {
       return this._enabled;
     }
-    this._enabled = false;
-    try {
-      this._enabled = Services.prefs.getBoolPref("dom.serviceWorkers.enabled");
-    } catch(e) {}
+    this._enabled = Services.prefs.getBoolPref("dom.serviceWorkers.enabled", false);
     return this._enabled;
   },
 
   init: function() {
     SystemAppProxy.addEventListener("mozAboutServiceWorkersContentEvent",
                                     AboutServiceWorkers);
   },
 
--- a/b2g/components/Bootstraper.jsm
+++ b/b2g/components/Bootstraper.jsm
@@ -70,16 +70,17 @@ this.Bootstraper = {
     * If a system app is already installed, uninstall it so that we can
     * cleanly replace it by the current one.
     */
   uninstallPreviousSystemApp: function() {
     // TODO: FIXME
     return Promise.resolve();
 
     let oldManifestURL;
+    // eslint-disable-next-line mozilla/use-default-preference-values
     try{
       oldManifestURL = Services.prefs.getCharPref("b2g.system_manifest_url");
     } catch(e) {
       // No preference set, so nothing to uninstall.
       return Promise.resolve();
     }
 
     let id = DOMApplicationRegistry.getAppLocalIdByManifestURL(oldManifestURL);
--- a/b2g/components/SignInToWebsite.jsm
+++ b/b2g/components/SignInToWebsite.jsm
@@ -89,22 +89,18 @@ XPCOMUtils.defineLazyModuleGetter(this, 
 XPCOMUtils.defineLazyModuleGetter(this, "SystemAppProxy",
                                   "resource://gre/modules/SystemAppProxy.jsm");
 
 // The default persona uri; can be overwritten with toolkit.identity.uri pref.
 // Do this if you want to repoint to a different service for testing.
 // There's no point in setting up an observer to monitor the pref, as b2g prefs
 // can only be overwritten when the profie is recreated.  So just get the value
 // on start-up.
-var kPersonaUri = "https://firefoxos.persona.org";
-try {
-  kPersonaUri = Services.prefs.getCharPref("toolkit.identity.uri");
-} catch(noSuchPref) {
-  // stick with the default value
-}
+var kPersonaUri = Services.prefs.getCharPref("toolkit.identity.uri",
+                                             "https://firefoxos.persona.org");
 
 // JS shim that contains the callback functions that
 // live within the identity UI provisioning frame.
 const kIdentityShimFile = "chrome://b2g/content/identity.js";
 
 // Type of MozChromeEvents to handle id dialogs.
 const kOpenIdentityDialog = "id-dialog-open";
 const kDoneIdentityDialog = "id-dialog-done";
--- a/browser/base/content/aboutaccounts/aboutaccounts.js
+++ b/browser/base/content/aboutaccounts/aboutaccounts.js
@@ -427,24 +427,19 @@ function show(id, childId) {
 // Migrate sync data from the default profile to the dev-edition profile.
 // Returns a promise of a true value if migration succeeded, or false if it
 // failed.
 function migrateToDevEdition(urlParams) {
   let defaultProfilePath;
   try {
     defaultProfilePath = window.getDefaultProfilePath();
   } catch (e) {} // no default profile.
-  let migrateSyncCreds = false;
-  if (defaultProfilePath) {
-    try {
-      migrateSyncCreds = Services.prefs.getBoolPref("identity.fxaccounts.migrateToDevEdition");
-    } catch (e) {}
-  }
 
-  if (!migrateSyncCreds) {
+  if (!defaultProfilePath ||
+      !Services.prefs.getBoolPref("identity.fxaccounts.migrateToDevEdition", false)) {
     return Promise.resolve(false);
   }
 
   Cu.import("resource://gre/modules/osfile.jsm");
   let fxAccountsStorage = OS.Path.join(defaultProfilePath, fxAccountsCommon.DEFAULT_STORAGE_FILENAME);
   return OS.File.read(fxAccountsStorage, { encoding: "utf-8" }).then(text => {
     let accountData = JSON.parse(text).accountData;
     updateDisplayedEmail(accountData);
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -2788,19 +2788,17 @@ var gMenuButtonBadgeManager = {
 // Setup the hamburger button badges for updates, if enabled.
 var gMenuButtonUpdateBadge = {
   enabled: false,
   badgeWaitTime: 0,
   timer: null,
   cancelObserverRegistered: false,
 
   init() {
-    try {
-      this.enabled = Services.prefs.getBoolPref("app.update.badge");
-    } catch (e) {}
+    this.enabled = Services.prefs.getBoolPref("app.update.badge", false);
     if (this.enabled) {
       this.badgeWaitTime = Services.prefs.getIntPref("app.update.badgeWaitTime",
                                                      345600); // 4 days
       Services.obs.addObserver(this, "update-staged", false);
       Services.obs.addObserver(this, "update-downloaded", false);
     }
   },
 
--- a/browser/components/customizableui/CustomizeMode.jsm
+++ b/browser/components/customizableui/CustomizeMode.jsm
@@ -37,19 +37,17 @@ XPCOMUtils.defineLazyModuleGetter(this, 
                                   "resource://gre/modules/LightweightThemeManager.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "SessionStore",
                                   "resource:///modules/sessionstore/SessionStore.jsm");
 
 let gDebug;
 XPCOMUtils.defineLazyGetter(this, "log", () => {
   let scope = {};
   Cu.import("resource://gre/modules/Console.jsm", scope);
-  try {
-    gDebug = Services.prefs.getBoolPref(kPrefCustomizationDebug);
-  } catch (ex) {}
+  gDebug = Services.prefs.getBoolPref(kPrefCustomizationDebug, false);
   let consoleOptions = {
     maxLogLevel: gDebug ? "all" : "log",
     prefix: "CustomizeMode",
   };
   return new scope.ConsoleAPI(consoleOptions);
 });
 
 var gDisableAnimation = null;
@@ -619,21 +617,18 @@ CustomizeMode.prototype = {
     let deck = this.document.getElementById("tab-view-deck");
     let toolboxRect = this.window.gNavToolbox.getBoundingClientRect();
     let height = toolboxRect.bottom;
     deck.style.setProperty("--toolbox-rect-height", `${height}`);
     deck.style.setProperty("--toolbox-rect-height-with-unit", `${height}px`);
   },
 
   maybeShowTip(aAnchor) {
-    let shown = false;
     const kShownPref = "browser.customizemode.tip0.shown";
-    try {
-      shown = Services.prefs.getBoolPref(kShownPref);
-    } catch (ex) {}
+    let shown = Services.prefs.getBoolPref(kShownPref, false);
     if (shown)
       return;
 
     let anchorNode = aAnchor || this.document.getElementById("customization-panelHolder");
     let messageNode = this.tipPanel.querySelector(".customization-tipPanel-contentMessage");
     if (!messageNode.childElementCount) {
       // Put the tip contents in the popup.
       let bundle = this.document.getElementById("bundle_browser");
--- a/browser/components/uitour/UITour.jsm
+++ b/browser/components/uitour/UITour.jsm
@@ -1790,20 +1790,18 @@ this.UITour = {
       case "appinfo":
         let props = ["defaultUpdateChannel", "version"];
         let appinfo = {};
         props.forEach(property => appinfo[property] = Services.appinfo[property]);
 
         // Identifier of the partner repack, as stored in preference "distribution.id"
         // and included in Firefox and other update pings. Note this is not the same as
         // Services.appinfo.distributionID (value of MOZ_DISTRIBUTION_ID is set at build time).
-        let distribution = "default";
-        try {
-          distribution = Services.prefs.getDefaultBranch("distribution.").getCharPref("id");
-        } catch (e) {}
+        let distribution =
+          Services.prefs.getDefaultBranch("distribution.").getCharPref("id", "default");
         appinfo["distribution"] = distribution;
 
         let isDefaultBrowser = null;
         try {
           let shell = aWindow.getShellService();
           if (shell) {
             isDefaultBrowser = shell.isDefaultBrowser(false);
           }
--- a/browser/modules/SocialService.jsm
+++ b/browser/modules/SocialService.jsm
@@ -206,26 +206,21 @@ var ActiveProviders = {
                  createInstance(Ci.nsISupportsString);
     string.data = JSON.stringify(this._providers);
     Services.prefs.setComplexValue("social.activeProviders",
                                    Ci.nsISupportsString, string);
   }
 };
 
 function migrateSettings() {
-  let activeProviders, enabled;
-  try {
-    activeProviders = Services.prefs.getCharPref("social.activeProviders");
-  } catch (e) {
-    // not set, we'll check if we need to migrate older prefs
-  }
+  let enabled;
   if (Services.prefs.prefHasUserValue("social.enabled")) {
     enabled = Services.prefs.getBoolPref("social.enabled");
   }
-  if (activeProviders) {
+  if (Services.prefs.getCharPref("social.activeProviders", "")) {
     // migration from fx21 to fx22 or later
     // ensure any *builtin* provider in activeproviders is in user level prefs
     for (let origin in ActiveProviders._providers) {
       let prefname;
       let manifest;
       let defaultManifest;
       try {
         prefname = getPrefnameFromOrigin(origin);
--- a/devtools/shared/touch/simulator-core.js
+++ b/devtools/shared/touch/simulator-core.js
@@ -16,29 +16,18 @@ var systemAppOrigin = (function () {
       Services.io.newURI(Services.prefs.getCharPref("b2g.system_manifest_url"))
                  .prePath;
   } catch (e) {
     // Fall back to default value
   }
   return systemOrigin;
 })();
 
-var threshold = 25;
-try {
-  threshold = Services.prefs.getIntPref("ui.dragThresholdX");
-} catch (e) {
-  // Fall back to default value
-}
-
-var delay = 500;
-try {
-  delay = Services.prefs.getIntPref("ui.click_hold_context_menus.delay");
-} catch (e) {
-  // Fall back to default value
-}
+var threshold = Services.prefs.getIntPref("ui.dragThresholdX", 25);
+var delay = Services.prefs.getIntPref("ui.click_hold_context_menus.delay", 500);
 
 function SimulatorCore(simulatorTarget) {
   this.simulatorTarget = simulatorTarget;
 }
 
 /**
  * Simulate touch events for platforms where they aren't generally available.
  */
--- a/mobile/android/components/DirectoryProvider.js
+++ b/mobile/android/components/DirectoryProvider.js
@@ -111,16 +111,17 @@ DirectoryProvider.prototype = {
     localePlugins.append("locale");
     if (!localePlugins.exists())
       return;
 
     let curLocale = "";
     try {
       curLocale = Services.prefs.getComplexValue("general.useragent.locale", Ci.nsIPrefLocalizedString).data;
     } catch (e) {
+      // eslint-disable-next-line mozilla/use-default-preference-values
       try {
         curLocale = Services.prefs.getCharPref("general.useragent.locale");
       } catch (ee) {
       }
     }
 
     if (curLocale) {
       let curLocalePlugins = localePlugins.clone();
--- a/security/sandbox/test/browser_content_sandbox_fs.js
+++ b/security/sandbox/test/browser_content_sandbox_fs.js
@@ -136,16 +136,17 @@ add_task(function*() {
 
   let level = 0;
   let prefExists = true;
 
   // Read the security.sandbox.content.level pref.
   // If the pref isn't set and we're running on Linux on !isNightly(),
   // exit without failing. The Linux content sandbox is only enabled
   // on Nightly at this time.
+  // eslint-disable-next-line mozilla/use-default-preference-values
   try {
     level = prefs.getIntPref("security.sandbox.content.level");
   } catch (e) {
     prefExists = false;
   }
 
   ok(prefExists, "pref security.sandbox.content.level exists");
   if (!prefExists) {
--- a/security/sandbox/test/browser_content_sandbox_syscalls.js
+++ b/security/sandbox/test/browser_content_sandbox_syscalls.js
@@ -129,16 +129,17 @@ add_task(function*() {
 
   let level = 0;
   let prefExists = true;
 
   // Read the security.sandbox.content.level pref.
   // If the pref isn't set and we're running on Linux on !isNightly(),
   // exit without failing. The Linux content sandbox is only enabled
   // on Nightly at this time.
+  // eslint-disable-next-line mozilla/use-default-preference-values
   try {
     level = prefs.getIntPref("security.sandbox.content.level");
   } catch (e) {
     prefExists = false;
   }
 
   ok(prefExists, "pref security.sandbox.content.level exists");
   if (!prefExists) {
--- a/toolkit/components/asyncshutdown/AsyncShutdown.jsm
+++ b/toolkit/components/asyncshutdown/AsyncShutdown.jsm
@@ -74,22 +74,18 @@ const isContent = Cc["@mozilla.org/xre/a
 
 // Display timeout warnings after 10 seconds
 const DELAY_WARNING_MS = 10 * 1000;
 
 
 // Crash the process if shutdown is really too long
 // (allowing for sleep).
 const PREF_DELAY_CRASH_MS = "toolkit.asyncshutdown.crash_timeout";
-var DELAY_CRASH_MS = 60 * 1000; // One minute
-try {
-  DELAY_CRASH_MS = Services.prefs.getIntPref(PREF_DELAY_CRASH_MS);
-} catch (ex) {
-  // Ignore errors
-}
+var DELAY_CRASH_MS = Services.prefs.getIntPref(PREF_DELAY_CRASH_MS,
+                                               60 * 1000); // One minute
 Services.prefs.addObserver(PREF_DELAY_CRASH_MS, function() {
   DELAY_CRASH_MS = Services.prefs.getIntPref(PREF_DELAY_CRASH_MS);
 }, false);
 
 /**
  * A set of Promise that supports waiting.
  *
  * Promise items may be added or removed during the wait. The wait will
@@ -202,22 +198,17 @@ function log(msg, prefix = "", error = n
         dump(prefix + error.stack + "\n");
       }
     }
   } catch (ex) {
     dump("INTERNAL ERROR in AsyncShutdown: cannot log message.\n");
   }
 }
 const PREF_DEBUG_LOG = "toolkit.asyncshutdown.log";
-var DEBUG_LOG = false;
-try {
-  DEBUG_LOG = Services.prefs.getBoolPref(PREF_DEBUG_LOG);
-} catch (ex) {
-  // Ignore errors
-}
+var DEBUG_LOG = Services.prefs.getBoolPref(PREF_DEBUG_LOG, false);
 Services.prefs.addObserver(PREF_DEBUG_LOG, function() {
   DEBUG_LOG = Services.prefs.getBoolPref(PREF_DEBUG_LOG);
 }, false);
 
 function debug(msg, error = null) {
   if (DEBUG_LOG) {
     log(msg, "DEBUG: ", error);
   }
--- a/toolkit/components/places/PlacesCategoriesStarter.js
+++ b/toolkit/components/places/PlacesCategoriesStarter.js
@@ -70,21 +70,18 @@ PlacesCategoriesStarter.prototype = {
           PlacesDBUtils.shutdown();
         }
         break;
       case TOPIC_GATHER_TELEMETRY:
         PlacesDBUtils.telemetry();
         break;
       case "idle-daily":
         // Once a week run places.sqlite maintenance tasks.
-        let lastMaintenance = 0;
-        try {
-          lastMaintenance =
-            Services.prefs.getIntPref("places.database.lastMaintenance");
-        } catch (ex) {}
+        let lastMaintenance =
+          Services.prefs.getIntPref("places.database.lastMaintenance", 0);
         let nowSeconds = parseInt(Date.now() / 1000);
         if (lastMaintenance < nowSeconds - MAINTENANCE_INTERVAL_SECONDS) {
           PlacesDBUtils.maintenanceOnIdle();
         }
         break;
       default:
         throw new Error("Trying to handle an unknown category.");
     }
--- a/toolkit/components/places/UnifiedComplete.js
+++ b/toolkit/components/places/UnifiedComplete.js
@@ -472,20 +472,17 @@ XPCOMUtils.defineLazyGetter(this, "Prefs
     store.suggestHistory = prefs.get(...PREF_SUGGEST_HISTORY);
     store.suggestBookmark = prefs.get(...PREF_SUGGEST_BOOKMARK);
     store.suggestOpenpage = prefs.get(...PREF_SUGGEST_OPENPAGE);
     store.suggestTyped = prefs.get(...PREF_SUGGEST_HISTORY_ONLYTYPED);
     store.suggestSearches = prefs.get(...PREF_SUGGEST_SEARCHES);
     store.maxCharsForSearchSuggestions = prefs.get(...PREF_MAX_CHARS_FOR_SUGGEST);
     store.prefillSitesEnabled = prefs.get(...PREF_PREFILL_SITES_ENABLED);
     store.prefillSitesExpireDays = prefs.get(...PREF_PREFILL_SITES_EXPIRE_DAYS);
-    store.keywordEnabled = true;
-    try {
-      store.keywordEnabled = Services.prefs.getBoolPref("keyword.enabled");
-    } catch (ex) {}
+    store.keywordEnabled = Services.prefs.getBoolPref("keyword.enabled", true);
 
     // If history is not set, onlyTyped value should be ignored.
     if (!store.suggestHistory) {
       store.suggestTyped = false;
     }
     store.defaultBehavior = types.concat("Typed").reduce((memo, type) => {
       let prefValue = store["suggest" + type];
       return memo | (prefValue &&
--- a/toolkit/components/places/nsPlacesExpiration.js
+++ b/toolkit/components/places/nsPlacesExpiration.js
@@ -788,21 +788,18 @@ nsPlacesExpiration.prototype = {
     return this._expireOnIdle;
   },
   get expireOnIdle() {
     return this._expireOnIdle;
   },
 
   _loadPrefs: Task.async(function* () {
     // Get the user's limit, if it was set.
-    try {
-      // We want to silently fail since getIntPref throws if it does not exist,
-      // and use a default to fallback to.
-      this._urisLimit = this._prefBranch.getIntPref(PREF_MAX_URIS);
-    } catch (ex) { /* User limit not set */ }
+    this._urisLimit = this._prefBranch.getIntPref(PREF_MAX_URIS,
+                                                  PREF_MAX_URIS_NOTSET);
 
     if (this._urisLimit < 0) {
       // Some testing code expects a pref change to be synchronous, so
       // temporarily set this to a large value, while we asynchronously update
       // to the correct value.
       this._urisLimit = 300000;
 
       // The user didn't specify a custom limit, so we calculate the number of
@@ -850,21 +847,18 @@ nsPlacesExpiration.prototype = {
       this._urisLimit = Math.ceil(optimalDatabaseSize / avgURISize);
     }
 
     // Expose the calculated limit to other components.
     this._prefBranch.setIntPref(PREF_READONLY_CALCULATED_MAX_URIS,
                                 this._urisLimit);
 
     // Get the expiration interval value.
-    try {
-      // We want to silently fail since getIntPref throws if it does not exist,
-      // and use a default to fallback to.
-      this._interval = this._prefBranch.getIntPref(PREF_INTERVAL_SECONDS);
-    } catch (ex) { /* User interval not set */ }
+    this._interval = this._prefBranch.getIntPref(PREF_INTERVAL_SECONDS,
+                                                 PREF_INTERVAL_SECONDS_NOTSET);
     if (this._interval <= 0) {
       this._interval = PREF_INTERVAL_SECONDS_NOTSET;
     }
   }),
 
   /**
    * Evaluates the real number of pages in the database and the value currently
    * used by the SQLite query planner.
--- a/toolkit/components/places/tests/unit/test_000_frecency.js
+++ b/toolkit/components/places/tests/unit/test_000_frecency.js
@@ -51,24 +51,18 @@ var searchTerm = "frecency";
 var results = [];
 var matchCount = 0;
 var now = Date.now();
 var prefPrefix = "places.frecency.";
 
 function* task_initializeBucket(bucket) {
   let [cutoffName, weightName] = bucket;
   // get pref values
-  var weight = 0, cutoff = 0;
-  try {
-    weight = prefs.getIntPref(prefPrefix + weightName);
-  } catch (ex) {}
-  try {
-    cutoff = prefs.getIntPref(prefPrefix + cutoffName);
-  } catch (ex) {}
-
+  var weight = prefs.getIntPref(prefPrefix + weightName, 0);
+  var cutoff = prefs.getIntPref(prefPrefix + cutoffName, 0);
   if (cutoff < 1)
     return;
 
   // generate a date within the cutoff period
   var dateInPeriod = (now - ((cutoff - 1) * 86400 * 1000)) * 1000;
 
   for (let [bonusName, visitType] of Object.entries(bonusPrefs)) {
     var frecency = -1;
--- a/toolkit/components/urlformatter/tests/unit/test_urlformatter.js
+++ b/toolkit/components/urlformatter/tests/unit/test_urlformatter.js
@@ -22,21 +22,19 @@ function run_test() {
     macutils = Cc["@mozilla.org/xpcom/mac-utils;1"].
                getService(Ci.nsIMacUtils);
   } catch (e) {}
   var appInfo = Cc["@mozilla.org/xre/app-info;1"].
                 getService(Ci.nsIXULAppInfo).
                 QueryInterface(Ci.nsIXULRuntime);
   var abi = macutils && macutils.isUniversalBinary ? "Universal-gcc3" : appInfo.XPCOMABI;
 
-  let channel = "default";
   let defaults = prefs.QueryInterface(Ci.nsIPrefService).getDefaultBranch(null);
-  try {
-    channel = defaults.getCharPref("app.update.channel");
-  } catch (e) {}
+  let channel = defaults.getCharPref("app.update.channel", "default");
+
   // Set distribution values.
   defaults.setCharPref("distribution.id", "bacon");
   defaults.setCharPref("distribution.version", "1.0");
 
   var upperUrlRaw = "http://%LOCALE%.%VENDOR%.foo/?name=%NAME%&id=%ID%&version=%VERSION%&platversion=%PLATFORMVERSION%&abid=%APPBUILDID%&pbid=%PLATFORMBUILDID%&app=%APP%&os=%OS%&abi=%XPCOMABI%";
   var lowerUrlRaw = "http://%locale%.%vendor%.foo/?name=%name%&id=%id%&version=%version%&platversion=%platformversion%&abid=%appbuildid%&pbid=%platformbuildid%&app=%app%&os=%os%&abi=%xpcomabi%";
   // XXX %APP%'s RegExp is not global, so it only replaces the first space
   var ulUrlRef = "http://" + locale + ".Mozilla.foo/?name=Url Formatter Test&id=urlformattertest@test.mozilla.org&version=1&platversion=2.0&abid=" + gAppInfo.appBuildID + "&pbid=" + gAppInfo.platformBuildID + "&app=urlformatter test&os=XPCShell&abi=" + abi;
--- a/toolkit/content/contentAreaUtils.js
+++ b/toolkit/content/contentAreaUtils.js
@@ -719,16 +719,17 @@ function promiseTargetFile(aFpP, /* opti
     fp.defaultString = getNormalizedLeafName(aFpP.fileInfo.fileName,
                                              aFpP.fileInfo.fileExt);
     appendFiltersForContentType(fp, aFpP.contentType, aFpP.fileInfo.fileExt,
                                 aFpP.saveMode);
 
     // The index of the selected filter is only preserved and restored if there's
     // more than one filter in addition to "All Files".
     if (aFpP.saveMode != SAVEMODE_FILEONLY) {
+      // eslint-disable-next-line mozilla/use-default-preference-values
       try {
         fp.filterIndex = prefBranch.getIntPref("save_converter_index");
       } catch (e) {
       }
     }
 
     let deferComplete = Promise.defer();
     fp.open(function(aResult) {
--- a/toolkit/content/widgets/scrollbox.xml
+++ b/toolkit/content/widgets/scrollbox.xml
@@ -819,21 +819,19 @@
                          onclick="_distanceScroll(event);"
                          onmousedown="if (event.button == 0) _startScroll(1);"
                          onmouseup="if (event.button == 0) _stopScroll();"
                          onmouseover="_continueScroll(1);"
                          onmouseout="_pauseScroll();"/>
     </content>
     <implementation implements="nsITimerCallback, nsIDOMEventListener">
       <constructor><![CDATA[
-        try {
-          this._scrollDelay = this._prefBranch
-                                  .getIntPref("toolkit.scrollbox.clickToScroll.scrollDelay");
-        } catch (ex) {
-        }
+        this._scrollDelay =
+          this._prefBranch.getIntPref("toolkit.scrollbox.clickToScroll.scrollDelay",
+                                      this._scrollDelay);
       ]]></constructor>
 
       <destructor><![CDATA[
         // Release timer to avoid reference cycles.
         if (this._scrollTimer) {
           this._scrollTimer.cancel();
           this._scrollTimer = null;
         }
--- a/toolkit/modules/Troubleshoot.jsm
+++ b/toolkit/modules/Troubleshoot.jsm
@@ -189,16 +189,17 @@ var dataProviders = {
                  getService(Ci.nsIHttpProtocolHandler).
                  userAgent,
       safeMode: Services.appinfo.inSafeMode,
     };
 
     if (AppConstants.MOZ_UPDATER)
       data.updateChannel = Cu.import("resource://gre/modules/UpdateUtils.jsm", {}).UpdateUtils.UpdateChannel;
 
+    // eslint-disable-next-line mozilla/use-default-preference-values
     try {
       data.vendor = Services.prefs.getCharPref("app.support.vendor");
     } catch (e) {}
     let urlFormatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
                        getService(Ci.nsIURLFormatter);
     try {
       data.supportURL = urlFormatter.formatURLPref("app.support.baseURL");
     } catch (e) {}
@@ -522,16 +523,17 @@ var dataProviders = {
     done(data);
   },
 
   accessibility: function accessibility(done) {
     let data = {};
     data.isActive = Cc["@mozilla.org/xre/app-info;1"].
                     getService(Ci.nsIXULRuntime).
                     accessibilityEnabled;
+    // eslint-disable-next-line mozilla/use-default-preference-values
     try {
       data.forceDisabled =
         Services.prefs.getIntPref("accessibility.force_disabled");
     } catch (e) {}
     done(data);
   },
 
   libraryVersions: function libraryVersions(done) {
--- a/toolkit/modules/UpdateUtils.jsm
+++ b/toolkit/modules/UpdateUtils.jsm
@@ -26,23 +26,19 @@ this.UpdateUtils = {
    * Read the update channel from defaults only.  We do this to ensure that
    * the channel is tightly coupled with the application and does not apply
    * to other instances of the application that may use the same profile.
    *
    * @param [optional] aIncludePartners
    *        Whether or not to include the partner bits. Default: true.
    */
   getUpdateChannel(aIncludePartners = true) {
-    let channel = AppConstants.MOZ_UPDATE_CHANNEL;
     let defaults = Services.prefs.getDefaultBranch(null);
-    try {
-      channel = defaults.getCharPref("app.update.channel");
-    } catch (e) {
-      // use default value when pref not found
-    }
+    let channel = defaults.getCharPref("app.update.channel",
+                                       AppConstants.MOZ_UPDATE_CHANNEL);
 
     if (aIncludePartners) {
       try {
         let partners = Services.prefs.getChildList("app.partner.").sort();
         if (partners.length) {
           channel += "-cck";
           partners.forEach(function(prefName) {
             channel += "-" + Services.prefs.getCharPref(prefName);
--- a/toolkit/mozapps/extensions/AddonManager.jsm
+++ b/toolkit/mozapps/extensions/AddonManager.jsm
@@ -632,18 +632,18 @@ function AddonType(aID, aLocaleURI, aLoc
 var gStarted = false;
 var gStartupComplete = false;
 var gCheckCompatibility = true;
 var gStrictCompatibility = true;
 var gCheckUpdateSecurityDefault = true;
 var gCheckUpdateSecurity = gCheckUpdateSecurityDefault;
 var gUpdateEnabled = true;
 var gAutoUpdateDefault = true;
-var gHotfixID = null;
-var gWebExtensionsMinPlatformVersion = null;
+var gHotfixID = "";
+var gWebExtensionsMinPlatformVersion = "";
 var gShutdownBarrier = null;
 var gRepoShutdownState = "";
 var gShutdownInProgress = false;
 var gPluginPageListener = null;
 
 /**
  * This is the real manager, kept here rather than in AddonManager to keep its
  * contents hidden from API users.
@@ -830,54 +830,45 @@ var AddonManagerInternal = {
         this.validateBlocklist();
       }
 
       if (!MOZ_COMPATIBILITY_NIGHTLY) {
         PREF_EM_CHECK_COMPATIBILITY = PREF_EM_CHECK_COMPATIBILITY_BASE + "." +
                                       Services.appinfo.version.replace(BRANCH_REGEXP, "$1");
       }
 
-      try {
-        gCheckCompatibility = Services.prefs.getBoolPref(PREF_EM_CHECK_COMPATIBILITY);
-      } catch (e) {}
+      gCheckCompatibility = Services.prefs.getBoolPref(PREF_EM_CHECK_COMPATIBILITY,
+                                                       gCheckCompatibility);
       Services.prefs.addObserver(PREF_EM_CHECK_COMPATIBILITY, this, false);
 
-      try {
-        gStrictCompatibility = Services.prefs.getBoolPref(PREF_EM_STRICT_COMPATIBILITY);
-      } catch (e) {}
+      gStrictCompatibility = Services.prefs.getBoolPref(PREF_EM_STRICT_COMPATIBILITY,
+                                                        gStrictCompatibility);
       Services.prefs.addObserver(PREF_EM_STRICT_COMPATIBILITY, this, false);
 
-      try {
-        let defaultBranch = Services.prefs.getDefaultBranch("");
-        gCheckUpdateSecurityDefault = defaultBranch.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY);
-      } catch (e) {}
-
-      try {
-        gCheckUpdateSecurity = Services.prefs.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY);
-      } catch (e) {}
+      let defaultBranch = Services.prefs.getDefaultBranch("");
+      gCheckUpdateSecurityDefault = defaultBranch.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY,
+                                                              gCheckUpdateSecurityDefault);
+
+      gCheckUpdateSecurity = Services.prefs.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY,
+                                                        gCheckUpdateSecurity);
       Services.prefs.addObserver(PREF_EM_CHECK_UPDATE_SECURITY, this, false);
 
-      try {
-        gUpdateEnabled = Services.prefs.getBoolPref(PREF_EM_UPDATE_ENABLED);
-      } catch (e) {}
+      gUpdateEnabled = Services.prefs.getBoolPref(PREF_EM_UPDATE_ENABLED, gUpdateEnabled);
       Services.prefs.addObserver(PREF_EM_UPDATE_ENABLED, this, false);
 
-      try {
-        gAutoUpdateDefault = Services.prefs.getBoolPref(PREF_EM_AUTOUPDATE_DEFAULT);
-      } catch (e) {}
+      gAutoUpdateDefault = Services.prefs.getBoolPref(PREF_EM_AUTOUPDATE_DEFAULT,
+                                                      gAutoUpdateDefault);
       Services.prefs.addObserver(PREF_EM_AUTOUPDATE_DEFAULT, this, false);
 
-      try {
-        gHotfixID = Services.prefs.getCharPref(PREF_EM_HOTFIX_ID);
-      } catch (e) {}
+      gHotfixID = Services.prefs.getCharPref(PREF_EM_HOTFIX_ID, gHotfixID);
       Services.prefs.addObserver(PREF_EM_HOTFIX_ID, this, false);
 
-      try {
-        gWebExtensionsMinPlatformVersion = Services.prefs.getCharPref(PREF_MIN_WEBEXT_PLATFORM_VERSION);
-      } catch (e) {}
+      gWebExtensionsMinPlatformVersion =
+        Services.prefs.getCharPref(PREF_MIN_WEBEXT_PLATFORM_VERSION,
+                                   gWebExtensionsMinPlatformVersion);
       Services.prefs.addObserver(PREF_MIN_WEBEXT_PLATFORM_VERSION, this, false);
 
       let defaultProvidersEnabled = Services.prefs.getBoolPref(PREF_DEFAULT_PROVIDERS_ENABLED, true);
       AddonManagerPrivate.recordSimpleMeasure("default_providers", defaultProvidersEnabled);
 
       // Ensure all default providers have had a chance to register themselves
       if (defaultProvidersEnabled) {
         for (let url of DEFAULT_PROVIDERS) {
--- a/toolkit/mozapps/extensions/LightweightThemeManager.jsm
+++ b/toolkit/mozapps/extensions/LightweightThemeManager.jsm
@@ -794,21 +794,18 @@ var _previewTimerCallback = {
 };
 
 /**
  * Called when any of the lightweightThemes preferences are changed.
  */
 function _prefObserver(aSubject, aTopic, aData) {
   switch (aData) {
     case "maxUsedThemes":
-      try {
-        _maxUsedThemes = _prefs.getIntPref(aData);
-      } catch (e) {
-        _maxUsedThemes = DEFAULT_MAX_USED_THEMES_COUNT;
-      }
+      _maxUsedThemes = _prefs.getIntPref(aData, DEFAULT_MAX_USED_THEMES_COUNT);
+
       // Update the theme list to remove any themes over the number we keep
       _updateUsedThemes(LightweightThemeManager.usedThemes);
       break;
   }
 }
 
 function _persistImages(aData, aCallback) {
   function onSuccess(key) {
--- a/toolkit/mozapps/extensions/content/extensions.js
+++ b/toolkit/mozapps/extensions/content/extensions.js
@@ -1882,16 +1882,17 @@ var gCategories = {
     this._search = this.get("addons://search/");
 
     var types = AddonManager.addonTypes;
     for (var type in types)
       this.onTypeAdded(types[type]);
 
     AddonManager.addTypeListener(this);
 
+    // eslint-disable-next-line mozilla/use-default-preference-values
     try {
       this.node.value = Services.prefs.getCharPref(PREF_UI_LASTCATEGORY);
     } catch (e) { }
 
     // If there was no last view or no existing category matched the last view
     // then the list will default to selecting the search category and we never
     // want to show that as the first view so switch to the default category
     if (!this.node.selectedItem || this.node.selectedItem == this._search)
--- a/toolkit/mozapps/extensions/nsBlocklistService.js
+++ b/toolkit/mozapps/extensions/nsBlocklistService.js
@@ -249,26 +249,17 @@ function getLocale() {
                                           Ci.nsIPrefLocalizedString).data;
   } catch (e) {}
 
   return gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
 }
 
 /* Get the distribution pref values, from defaults only */
 function getDistributionPrefValue(aPrefName) {
-  var prefValue = "default";
-
-  var defaults = gPref.getDefaultBranch(null);
-  try {
-    prefValue = defaults.getCharPref(aPrefName);
-  } catch (e) {
-    // use default when pref not found
-  }
-
-  return prefValue;
+  return gPref.getDefaultBranch(null).getCharPref(aPrefName, "default");
 }
 
 /**
  * Parse a string representation of a regular expression. Needed because we
  * use the /pattern/flags form (because it's detectable), which is only
  * supported as a literal in JS.
  *
  * @param  aStr
--- a/toolkit/mozapps/extensions/test/xpcshell/test_pref_properties.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_pref_properties.js
@@ -206,16 +206,16 @@ function run_test() {
   // Change the pref and make sure the property is updated
   hotfixID = "hotfix2@tests.mozilla.org";
   Services.prefs.setCharPref("extensions.hotfix.id", hotfixID);
   do_check_eq(AddonManager.hotfixID, hotfixID);
   // Test an invalid pref value
   hotfixID = 99;
   Services.prefs.deleteBranch("extensions.hotfix.id");
   Services.prefs.setIntPref("extensions.hotfix.id", hotfixID);
-  do_check_eq(AddonManager.hotfixID, null);
+  do_check_eq(AddonManager.hotfixID, "");
   Services.prefs.clearUserPref("extensions.hotfix.id");
 
   // After removing the listener, ensure we get no further events.
   gManagerEventsListener.expect([]);
   AddonManager.updateEnabled = false;
   gManagerEventsListener.checkExpected();
 }