Guest User

Untitled

a guest
Oct 22nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. # Compile it with: crystal build --prelude=empty --emit llvm-ir noprelude_exception.cr
  2.  
  3. lib LibC
  4. alias SizeT = UInt64
  5. fun printf(format : UInt8*, ...) : Int32
  6. fun exit(exit_code : Int32) : NoReturn
  7. end
  8.  
  9. require "callstack/lib_unwind"
  10.  
  11. struct UInt64
  12. def self.zero
  13. 0
  14. end
  15. end
  16.  
  17. class String
  18. def to_unsafe
  19. pointerof(@c)
  20. end
  21. end
  22.  
  23. fun __crystal_personality(version : Int32, actions : LibUnwind::Action, exception_class : UInt64, exception_object : LibUnwind::Exception*, context : Void*) : LibUnwind::ReasonCode
  24. return LibUnwind::ReasonCode::CONTINUE_UNWIND
  25. end
  26.  
  27. @[Raises]
  28. fun __crystal_raise(unwind_ex : LibUnwind::Exception*) : NoReturn
  29. ret = LibUnwind.raise_exception(unwind_ex)
  30. LibC.printf "Failed to raise an exception: %d\n".to_unsafe, ret
  31. #CallStack.print_backtrace
  32. LibC.exit(ret.value)
  33. end
  34.  
  35. def raise(str : String) : NoReturn
  36. unwind_ex = LibUnwind::Exception.new
  37. unwind_ex.exception_class = LibC::SizeT.zero
  38. unwind_ex.exception_cleanup = LibC::SizeT.zero
  39. unwind_ex.exception_object = str.object_id
  40. unwind_ex.exception_type_id = str.crystal_type_id
  41. __crystal_raise(pointerof(unwind_ex))
  42. end
  43.  
  44. begin
  45. var = 2
  46. LibC.printf("in begin: var = %d\n", var)
  47. raise "I'm an exception!"
  48. ensure
  49. var = 3
  50. LibC.printf("in ensure: var = %d\n", var)
  51. end
  52.  
  53. LibC.printf("after: var = %d\n", var)
Add Comment
Please, Sign In to add comment