// 工作中使用:
    //需求: 统计年龄总和

    1. val list = List("1 zhangsan 20 shenzhen","2 lisi shenzhen"," wagnwu 20 shenzhen","3 zhangsan 20 ")
    2. // 工作中使用:
    3. //需求: 统计年龄总和
    4. println(list.map(line => {
    5. val arr = line.split(" ")
    6. Try(arr(2).toInt).getOrElse(0)
    7. }).sum)
    8. }
    1. package tcode.chapter09
    2. import java.sql.{Connection, DriverManager, PreparedStatement}
    3. import scala.util.Try
    4. object $01_Exception {
    5. /**
    6. * java中的异常处理:
    7. * 1、捕获异常: try{..}catch(..){..}finally{...}
    8. * 2、抛出异常: throw new XXXException + throws XXXException
    9. * scala中异常处理:
    10. * 1、捕获异常:
    11. * 1、try{..}catch{..}finally{...} <用于获取外部资源链接的场景>
    12. * 2、Try(代码块).getOrElse(默认值) 【如果代码块执行成功则返回代码块的执行结果,如果代码块执行失败则返回默认值】 <常用>
    13. * Try有两个子类: Success、Failture
    14. * Success: 代表代码执行成功,代码执行结果封装在Success中
    15. * Failture: 代表代码执行失败
    16. * 2、抛出异常: throw new XXXException [scala中抛出异常不需要在方法名后面通过throws声明异常.scala中没有throws关键字] <不用>
    17. *
    18. */
    19. def main(args: Array[String]): Unit = {
    20. println(m1(10, 0))
    21. val list = List("1 zhangsan 20 shenzhen","2 lisi shenzhen"," wagnwu 20 shenzhen","3 zhangsan 20 ")
    22. // 工作中使用:
    23. //需求: 统计年龄总和
    24. println(list.map(line => {
    25. val arr = line.split(" ")
    26. Try(arr(2).toInt).getOrElse(0)
    27. }).sum)
    28. }
    29. def m1(a:Int,b:Int) = {
    30. /* if(b==0) throw new Exception("被除数不能为0")
    31. a/b*/
    32. try{
    33. a/b
    34. }catch {
    35. case e:Exception => 0
    36. }finally {
    37. //...
    38. }
    39. }
    40. def jdbc(): Unit = {
    41. var connnection:Connection = null
    42. var statement:PreparedStatement = null
    43. try{
    44. connnection = DriverManager.getConnection("....")
    45. statement = connnection.prepareStatement("insert into person values(?,?,?)")
    46. statement.setString(1,"")
    47. statement.setString(2,"")
    48. statement.setString(3,"")
    49. statement.executeUpdate()
    50. }catch {
    51. case e:Exception =>
    52. }finally {
    53. if(statement!=null)
    54. statement.close()
    55. if(connnection!=null)
    56. connnection.close()
    57. }
    58. }
    59. }