Runtime
Runtime
A program execution environment. Node.js, JVM, Python interpreter.
Runtime
A program execution environment. Node.js, JVM, Python interpreter.
Runtime refers to the period during which a program is executing, or the environment required to execute a program. In the narrow sense, it refers to the point at which a program is loaded into memory and instructions are executed on the CPU; in the broad sense, it refers to the entire execution environment needed for code to run, including libraries, memory managers, garbage collectors, and so on. The runtime environment acts as an intermediate layer between the program and the operating system, and is responsible for hardware abstraction and resource management.
Compile Time and Runtime are the two most important points in time in programming. Compile time is the point at which source code is converted into machine code or bytecode, and problems such as syntax errors and type mismatches are discovered at this stage. Runtime, on the other hand, is the point at which the compiled program is actually executed. Errors such as division by zero, null references, array index out of bounds, and out of memory occur at runtime. Statically typed languages such as TypeScript and Java catch more errors at compile time, which improves runtime stability.
There are several representative runtime environments. The JVM (Java Virtual Machine) executes Java bytecode and provides JIT compilation, garbage collection, and memory management. Node.js is based on the V8 JavaScript engine, enables JavaScript to run on the server, and supports event-driven asynchronous I/O. A web browser has a built-in JavaScript engine (V8, SpiderMonkey, etc.) and executes client-side scripts. The Python interpreter converts Python code into bytecode and then executes it, and there are various implementations such as CPython and PyPy.
Runtime error handling is the core of developing stable programs. Because runtime errors occur unexpectedly while a program is running, exceptions must be caught with try-catch blocks and handled appropriately. When an error occurs, the cause of the error and the call path can be traced through the stack trace. In production environments, monitoring tools such as Sentry and Datadog are used to collect and analyze runtime errors in real time, and error logging and alerting systems are built to respond quickly.
# λ€μν λ°νμ μλ¬ μ νκ³Ό μ²λ¦¬ λ°©λ²
# 1. ZeroDivisionError - 0μΌλ‘ λλκΈ°
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("μ€λ₯: 0μΌλ‘ λλ μ μμ΅λλ€")
return None
divide(10, 0) # λ°νμμ μλ¬ λ°μ
# 2. IndexError - λ°°μ΄ μΈλ±μ€ μ΄κ³Ό
def get_element(arr, index):
try:
return arr[index]
except IndexError:
print(f"μ€λ₯: μΈλ±μ€ {index}κ° λ²μλ₯Ό λ²μ΄λ¬μ΅λλ€")
return None
numbers = [1, 2, 3]
get_element(numbers, 10) # λ°νμμ μλ¬ λ°μ
# 3. TypeError - νμ
λΆμΌμΉ
def add_numbers(a, b):
try:
return a + b
except TypeError as e:
print(f"νμ
μ€λ₯: {e}")
return None
add_numbers("hello", 5) # str + int μ°μ° λΆκ°
# 4. μ’
ν© μλ¬ νΈλ€λ§
def process_data(data):
try:
result = data["value"] / data["count"]
return result
except KeyError as e:
print(f"νμ ν€κ° μμ΅λλ€: {e}")
except ZeroDivisionError:
print("countκ° 0μ
λλ€")
except Exception as e:
print(f"μμμΉ λͺ»ν μ€λ₯: {e}")
finally:
print("μ²λ¦¬ μλ£") # νμ μ€ν
// JavaScript λ°νμ μλ¬ μ²λ¦¬
// 1. ReferenceError - μ μλμ§ μμ λ³μ μ°Έμ‘°
function checkVariable() {
try {
console.log(undefinedVar); // ReferenceError
} catch (error) {
console.error('λ³μκ° μ μλμ§ μμμ΅λλ€:', error.message);
}
}
// 2. TypeError - null/undefined μμ± μ κ·Ό
function getUserName(user) {
try {
// userκ° nullμ΄λ©΄ λ°νμ μλ¬ λ°μ
return user.name.toUpperCase();
} catch (error) {
if (error instanceof TypeError) {
console.error('μ μ μ λ³΄κ° μ ν¨νμ§ μμ΅λλ€');
return 'Unknown';
}
throw error; // λ€λ₯Έ μλ¬λ λ€μ throw
}
}
getUserName(null); // TypeError λ°μ
// 3. λΉλκΈ° μλ¬ μ²λ¦¬ (Promise)
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP μ€λ₯: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('λ°μ΄ν° κ°μ Έμ€κΈ° μ€ν¨:', error.message);
return null;
}
}
// 4. 컀μ€ν
μλ¬ ν΄λμ€
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
function validateAge(age) {
if (age < 0 || age > 150) {
throw new ValidationError('λμ΄κ° μ ν¨νμ§ μμ΅λλ€', 'age');
}
}
// Java λ°νμ μλ¬ μ²λ¦¬ (JVM νκ²½)
public class RuntimeExample {
public static void main(String[] args) {
// 1. NullPointerException
try {
String str = null;
int length = str.length(); // λ°νμ μλ¬!
} catch (NullPointerException e) {
System.out.println("null μ°Έμ‘° μλ¬: " + e.getMessage());
}
// 2. ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
int value = arr[10]; // μΈλ±μ€ μ΄κ³Ό
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("λ°°μ΄ μΈλ±μ€ μ΄κ³Ό");
e.printStackTrace(); // μ€ν νΈλ μ΄μ€ μΆλ ₯
}
// 3. ClassCastException
try {
Object obj = "Hello";
Integer num = (Integer) obj; // μλͺ»λ νλ³ν
} catch (ClassCastException e) {
System.out.println("νλ³ν μλ¬");
}
// 4. try-with-resources (리μμ€ μλ ν΄μ )
try (BufferedReader reader = new BufferedReader(
new FileReader("config.txt"))) {
String line = reader.readLine();
} catch (IOException e) {
System.out.println("νμΌ μ½κΈ° μ€ν¨");
}
}
}
Interviewer:
"Please explain the difference between a compile error and a runtime error, and give an example of each."
Candidate:
"A compile error occurs at the stage of compiling the source code. It is a problem such as a syntax error or a type mismatch, and is discovered before the program is run. For example, in Java, this is the case when you forget a semicolon or use a variable that has not been declared."
Candidate:
"A runtime error occurs while the program is running. NullPointerException, division by zero, and array index out of bounds are typical examples. Because it passes compilation but occurs in unexpected situations during actual execution, it can be harder to debug."
Interviewer:
"Then what are some ways to reduce runtime errors?"
Candidate:
"There are several methods. First, using statically typed languages such as TypeScript or Java catches more errors at compile time. Second, edge cases are verified in advance with unit tests. Third, NPEs are prevented with Optional or null-safety features. Fourth, input values are validated through defensive programming, and appropriate exception handling is applied."
Senior Developer:
"I just got a runtime error alert from Sentry for the production server. The 'Cannot read property 'id' of undefined' error suddenly spiked on a specific API."
Junior Developer:
"Looking at the stack trace, it occurred in the getProfile method of UserService. Did we deploy that part recently?"
Senior Developer:
"Yesterday there was a migration that changed the user data structure. It seems the error occurs because the field is missing when an old version of the app calls the new API. We should have applied Optional Chaining..."
Junior Developer:
"We can fix it with user?.profile?.id and also set a default value. And we should also add fallback logic for when a runtime error occurs."
Senior Developer:
"Right. After deploying the hotfix, let's also add API response schema validation logic. If we do runtime type checking with a library like Zod or Joi, we can detect this kind of problem in advance."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Runtime errors can halt a program, so they must be handled appropriately with try-catch. However, avoid empty catch blocks that ignore all exceptions. Log the error, provide appropriate feedback to the user when necessary, and handle unrecoverable errors explicitly.
Even identical code can behave differently depending on the runtime environment. Be aware of differences depending on the Node.js version, JVM version, and browser type. To prevent "it works on my machine..." problems caused by differences between development and production environments, consider containerization such as Docker.
Continuously monitor the runtime environment's memory usage, CPU load, and response time. Memory leaks and performance degradation appear only at runtime. Use APM (Application Performance Monitoring) tools such as Datadog, New Relic, and Sentry to track the runtime state in real time.