android学习笔记--(1)

[size=medium;]1.Android代码规范[/size]

[size=medium;]1.1Exception异常:[/size]

[size=medium;](1)不要忽略处理捕获到的任何异常,若非要忽略则应注明忽略的原因;[/size]

[size=medium;](2)要准备捕获各类异常,不能笼统使用exception通用异常;[/size]

[size=medium;]Error code void setServerPort(String value) { try { serverPort = Integer.parseInt(value); } catch (NumberFormatException e) { } } try { someComplicatedIOFunction(); // may throw IOException someComplicatedParsingFunction(); // may throw ParsingException someComplicatedSecurityFunction(); // may throw SecurityException // phew, made it all the way } catch (Exception e) { // I'll just catch all exceptions handleError(); // with one generic handler! }

[size=medium;]

[/size][/size]

[size=medium;]Right codes[/size]

void setServerPort(String value) throws NumberFormatException { serverPort = Integer.parseInt(value); } void setServerPort(String value) throws ConfigurationException { try { serverPort = Integer.parseInt(value); } catch (NumberFormatException e) { throw new ConfigurationException("Port " + value + " is not valid."); } } /** Set port. If value is not a valid number, 80 is substituted. */ void setServerPort(String value) { try { serverPort = Integer.parseInt(value); } catch (NumberFormatException e) { serverPort = 80; // default port for server } } /** Set port. If value is not a valid number, die. */ void setServerPort(String value) { try { serverPort = Integer.parseInt(value); } catch (NumberFormatException e) { throw new RuntimeException("port " + value " is invalid, ", e); } } /** If value is not a valid number, original port number is used. */ void setServerPort(String value) { try { serverPort = Integer.parseInt(value); } catch (NumberFormatException e) { // Method is documented to just ignore invalid user input. // serverPort will just be unchanged. } }

 

你可能感兴趣的:(android)