What mechanisms exist for disrupting the operation of a specific part of a project?
sobes.tech AI
Answer from AI
-
Exceptions: Allow stopping code execution when an error occurs and transferring control to
begin/rescue/ensureblocks.begin # Code that may cause an error result = 1 / 0 rescue ZeroDivisionError => e # Handling specific error puts "Division by zero error: #{e.message}" # Possibly logging or alternative execution rescue StandardError => e # Handling other standard errors puts "Another error occurred: #{e.message}" ensure # Code that always executes, regardless of error presence puts "End of block" end -
Raise: Explicitly raising an exception, for both standard and custom error classes.
# Raising a standard exception raise "Something went wrong" # Raising with a specific error class raise MyCustomError, "Invalid value" -
exit,abort,Kernel#exit!: Methods to terminate program execution.exit!terminates immediately without callingat_exithandlers.# Normal program termination exit(0) # 0 indicates successful termination # Termination with an error abort("Terminating due to a critical error") # Forced termination Kernel.exit!(1) -
Thread#raise: Allows raising an exception in another thread.
thread = Thread.new do begin loop { sleep 1 } rescue => e puts "Thread caught: #{e.class}" end end sleep 2 thread.raise StandardError, "Stop the thread" thread.join -
Programming errors (logical, syntactic): Incorrectly written code can lead to runtime failures.
# Syntactic error (missing end) def my_method puts "Hello" # Logical error (infinite loop) while true puts "Loop" end -
Operating system signals (SIGTERM, SIGINT, etc.): Can interrupt program execution from outside.
# Simple example handling SIGINT (Ctrl+C) Signal.trap("INT") { puts "\nSIGINT caught. Exiting..."; exit } loop { sleep 1 } -
Assertions (especially during development and testing): Mechanisms to verify conditions, throwing exceptions or performing other actions when violated. In Ruby, often implemented with testing libraries.
# Example using MiniTest library require 'minitest/autorun' class MyTest < Minitest::Test def test_division # Assertion: division of 4 by 2 equals 2 assert_equal 2, 4 / 2 # Assertion: division by zero should raise ZeroDivisionError assert_raises(ZeroDivisionError) { 1 / 0 } end end