Skip to content

Compilation Processes and Exception of three languages

Comparison of Compilation/Execution Processes in Other Languages:

C

  • Type: Compiled language
  • Process: Preprocessing → Compiling → Assembling → Linking
  • Output: Binary executable

C++

  • Type: Compiled language
  • Process: Almost the same as C, but uses a more advanced compiler (e.g., g++, clang++)
  • Output: Binary executable
  • Note: Supports classes, templates, RAII, etc., so the compilation process can be more complex.

Java

  • Type: Semi-compiled (interpreted + compiled)
  • Process:

.java source code
      ↓ (javac compiler)
   .class bytecode
      ↓ (JVM interpreter or JIT compiler)
   Runs on JVM
- The Java compiler translates source code into platform-independent bytecode (.class files). - The JVM either interprets or compiles (JIT) the bytecode at runtime. - Output: Bytecode (.class)


Python

  • Type: Interpreted language
  • Process:

.py source code
     ↓ (interpreter)
  Bytecode (.pyc)
     ↓ (Python virtual machine executes)
  Runs directly
- Python first compiles code into bytecode (.pyc), which is then interpreted by the Python VM (like CPython). - Output: Not a standalone binary, needs the Python interpreter to run.


Summary Comparison Table:

Language Type Compilation/Execution Process Output Format
C Compiled Preprocessing → Compiling → Assembling → Linking Native binary executable
C++ Compiled Same as C (with advanced features) Native binary executable
Java Semi-compiled Compiles to bytecode → JVM interprets or JIT compiles Bytecode (.class)
Python Interpreted (+bytecode) Source → Bytecode → Interpreter runs Bytecode (.pyc, not standalone)

Example

1. C++ (g++ / clang++)

Stage 0 — Pre-processing • Header not found

#include "missing.hpp"
int main() {}

• Mismatched directives

#ifdef FLAG
int main(){}
#endif
#endif    // extra #endif

Stage 1 — Compiling (source → .s) • Syntax error

int main(){ std::cout << "hi" }   // forgot ‘;’

• Undeclared identifier

int main(){ unknownVar = 1; }

Extra: Template-instantiation error

template<typename T> void f(T*){}
int main(){ f(42); }  // no pointer overload

Stage 2 — Assembling (.s → .o) • Illegal instruction / directive

asm("bad_op %eax");

• Misspelled pseudo-op

asm(".secton .data");  // typo

Stage 3 — Linking (.o → exe) • Undefined reference

void foo();
int main(){ foo(); }   // foo not linked

• Multiple definition

// in a header included twice
int g = 0;   // should be ‘extern int g;’

Stage 4 — Run-time • Segmentation fault

int* p=nullptr; *p = 1;

• Stack overflow

void f(){ f(); } int main(){ f(); }

────────────────────────────────────────

2. Java (OpenJDK)

Stage 0 — Compilation (javac → .class) • Syntax error

class T{ public static void main(String[] a){ System.out.println("hi") } }

• Type mismatch

int x = "hello";

Extra: Unhandled checked exception

void m(){ throw new IOException(); }   // must declare or catch

Stage 1 — Class loading / linking (JVM start-up) • ClassNotFoundException

Class.forName("com.missing.Foo");

• NoSuchMethodError (ABI drift) // compile against v1; run with v2 that dropped the method.

Stage 2 — Execution (interpreted / JIT) • NullPointerException

String s=null; s.length();

• ArrayIndexOutOfBoundsException

int[] a=new int[1]; a[3]=7;

Extra: OutOfMemoryError

List<byte[]> list=new ArrayList<>();
while(true) list.add(new byte[1<<20]);

────────────────────────────────────────

3. Python 3 (CPython)

Stage 0 — Parsing / byte-compilation (.py → .pyc) • SyntaxError

if True
    pass

• IndentationError

def f():
print("bad indent")

Stage 1 — Import time / bytecode setup • ModuleNotFoundError

import not_existing

• NameError (late binding)

def f(): print(x)
f()         # x undefined

Stage 2 — Run-time interpretation • TypeError

3 + "4"

• ZeroDivisionError

1 / 0

Extra: AttributeError

(42).upper()


Exception

  1. Java assert

  2. Java throw (explicit exception)

  3. C++ throw (explicit exception)

  4. C++ assert

  5. Python raise


  1. Java — assert
// AssertDemo.java
public class AssertDemo {
    public static void main(String[] args) {
        int x = -1;

        // Checked only when the JVM is started with -ea / -enableassertions
        assert x > 0 : "x must be positive";

        System.out.println("x = " + x);
    }
}

  1. Java — throw an exception
public class Person {
    private int age;

    public void setAge(int age) {
        if (age < 0) {
            // Explicitly throw a runtime exception
            throw new IllegalArgumentException("age must be >= 0");
        }
        this.age = age;
    }
}
try {
    // 可能抛出异常的代码
    int x = 10 / 0;
} catch (ArithmeticException e) {
    System.err.println("Divide by zero!");
} finally {
    System.out.println("Always executed (e.g., close files).");
}

  1. C++ — throw an exception
#include <iostream>
#include <stdexcept>

double divide(int a, int b) {
    if (b == 0) {
        throw std::runtime_error("divide by zero");
    }
    return static_cast<double>(a) / b;
}

int main() {
    try {
        std::cout << divide(10, 0) << '\n';
    } catch (const std::exception& ex) {
        std::cerr << "Error: " << ex.what() << '\n';
    }
}

  1. C++ — assert
#include <cassert>
#include <cmath>   // for M_PI

double circleArea(int r) {
    // If r <= 0 the program aborts in debug builds (when NDEBUG is NOT defined)
    assert(r > 0 && "radius must be positive");
    return M_PI * r * r;
}

  1. Python — raise
def set_age(age: int):
    if age < 0:
        raise ValueError("age must be non-negative")
    print(f"Age set to {age}")

set_age(-3)

Execution raises ValueError: age must be non-negative.


  1. Python - assert
def sqrt(x: float) -> float:
    assert x >= 0, "x must be non-negative"
    return x ** 0.5
try:
    content = open("data.txt").read()
except FileNotFoundError:
    print("File missing")
else:
    process(content)      # 只有成功读取时才会跑到这里
finally:
    print("Done")

Java (checked + unchecked exceptions) • NullPointerException — reference points to null and is dereferenced • IllegalArgumentException — method argument fails validation • IllegalStateException — object is in an inappropriate state for the call • ArrayIndexOutOfBoundsException / IndexOutOfBoundsException — bad index on array or list • NumberFormatException — string cannot be parsed to a number • ArithmeticException — math error such as divide by zero • ClassCastException — invalid type cast • FileNotFoundException — file path does not exist (checked) • IOException — general I/O failure (checked) • SQLException — database access failure (checked) • InterruptedException — thread was interrupted while waiting (checked) • ConcurrentModificationException — collection modified while iterating • UnsupportedOperationException — method not supported by the object • AssertionError — assert statement failed

C++ (standard exceptions) • std::runtime_error — generic run-time error • std::logic_error — program-logic violation caught by the library • std::invalid_argument — bad argument value • std::out_of_range — index outside valid range • std::length_error — attempt to create an object that is too large • std::overflow_error / std::underflow_error — numeric overflow / underflow • std::bad_alloc — memory allocation failure (new threw) • std::bad_cast — failed dynamic_cast​ • std::bad_typeid — invalid use of typeid​ • std::ios_base::failure — I/O stream error • std::system_error — error originating from the operating system • std::future_error — invalid use of std::future/std::promise (Outside the exception system, a segmentation fault is the classic fatal error.)

Python (built-in exceptions) • ValueError — argument has right type but inappropriate value • TypeError — operation applied to an object of wrong type • KeyError — missing key in dict • IndexError — sequence subscript out of range • NameError — identifier not found in the current scope • AttributeError — object lacks the requested attribute • ImportError / ModuleNotFoundError — import failed • FileNotFoundError — file or directory does not exist • IOError / OSError — general I/O or operating-system failure • ZeroDivisionError — division or modulo by zero • RuntimeError — generic run-time error not covered by other categories • NotImplementedError — abstract method or planned feature not implemented • AssertionError — assert statement failed • MemoryError — out of memory • StopIteration — iterator has no more items (signals loop termination) • KeyboardInterrupt — user pressed Ctrl+C • SystemExit — sys.exit() called (terminates interpreter)

public static <T extends Comparable<? super T>> T maximum_c(T[] values)

public static <E extends Comparable<? super E>, C extends Collection> int findElement(C list, E element)