from sys import stdin
input = iter(stdin.readlines()).__next__

class wlist(list):
    def __setitem__(self, key, value):
        return super().__setitem__(key % len(self), value)

t = int(input())
for _ in range(t):
    n, m, a, b = map(int, input().split())

    if n * a == m * b:
        print("YES")
        mat = [wlist([0 for _ in range(m)]) for _ in range(n)]
        i = 0
        for ri in range(n):
            for ci in range(i, i + a):
                mat[ri][ci] = 1
            i += a
            print(*mat[ri], sep = '')
    else:
        print("NO")


t = int(input())
for i in range(t):
    n,m,a,b = map(int,input().split())
    if m/n == a/b:
        print("YES")
        x = ""
        for k in range(a):
            x = x+"1"
        for l in range(m-a):
            x += "0"
        print(x)
        for j in range(n-1):
            Rfirst = x[0 : m-((j+1)*a)%m]
            Rsecond = x[m-((j+1)*a)%m : ]
            print(Rsecond+Rfirst)
    else:
        print("NO")


t = int(input())
for i in range(t):
    n,m,a,b = map(int,input().split())
    if m/n == a/b:
        print("YES")
        for j in range(n):
            x = ""
            for k in range(a):
                flag = 0
                for l in range(j):
                    x = x+"0"
                x = x+"1"
                for l in range(m//a - 1):
                    if len(x) == n:
                        flag = 1
                        break
                    x += "0"
                    if len(x) == n:
                        flag = 1
                        break
                if flag == 1:
                    break
            print(x)
    else:
        print("NO")


t = int(input())
for i in range(t):
    n,m,a,b = map(int,input().split())
    if m/n == a/b:
        print("YES")
        x = ""
        for k in range(a):
            x = x+"1"
            for l in range(m//a - 1):
                x += "0"
        print(x)
        for j in range(n-1):
            Rfirst = x[0 : m-j-1]
            Rsecond = x[m-j-1 : ]
            print(Rsecond+Rfirst)
    else:
        print("NO")


t = int(input())
for i in range(t):
    n,m,a,b = map(int,input().split())
    if m/n == a/b:
        print("YES")
        for j in range(n):
            x = ""
            for k in range(a):
                flag = 0
                for l in range(j):
                    x = x+"0"
                x = x+"1"
                for l in range(m//a - 1):
                    if len(x) == n:
                        flag = 1
                        break
                    x += "0"
                    if len(x) == n:
                        flag = 1
                        break
                if flag = 1:
                    break
            print(x)
    else:
        print("NO")


t = int(input())
for i in range(t):
    n,m,a,b = map(int,input().split())
    if m/n == a/b:
        print("YES")
        x = ""
        for k in range(a):
            x = x+"1"
        for l in range(m-a):
            x += "0"
        print(x)
        for j in range(n-1):
            Rfirst = x[0 : m-(j+1)*a]
            Rsecond = x[m-(j+1)*a : ]
            print(Rsecond+Rfirst)
    else:
        print("NO")


import io
import os
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def solve():
    n,m,a,b=map(int,input().split())
    if n*a!=m*b:
        print("NO")
    else:
        z=[["0" for j in range(m)] for i in range(n)]
        k=0
        i=0
        j=0
        while k<=n*m:
            for l in range(a):
                z[i][j]="1"
                k+=1
                j=(j+1)%m
            i=(i+1)%n
            k+=1
        print("YES")
        for i in z:
            print("".join(i))
def main():
    for t in range(int(input())):
        solve()
if __name__=="__main__":
    main()


import io
import os
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def solve():
    n,m,a,b=map(int,input().split())
    if n*a!=m*b:
        print("NO")
    else:
        z=[["0" for j in range(m)] for i in range(n)]
        k=0
        i=0
        j=0
        while k<=n*a:
            for l in range(a):
                z[i][j]="1"
                k+=1
                j=(j+1)%m
            i=(i+1)%n
        print("YES")
        for i in z:
            print("".join(i))
def main():
    for t in range(int(input())):
        solve()
if __name__=="__main__":
    main()


import io
import os
from sys import stdout
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
print=stdout.write
def solve():
    n,m,a,b=map(int,input().split())
    if n*a!=m*b:
        print("NO\n")
    else:
        z=[["0" for j in range(m)] for i in range(n)]
        k=0
        i=0
        j=0
        while k<=n*a:
            for l in range(a):
                z[i][j]="1"
                k+=1
                j=(j+1)%m
            i=(i+1)%n
        print("YES\n")
        for i in z:
            print("".join(i)+"\n")
def main():
    for t in range(int(input())):
        solve()
if __name__=="__main__":
    main()


def solve():
    if not n*a == m * b:
        print("NO")
        return
    ans = [[0 for _ in range(m)] for _ in range(n)]
    colsum = [0]*m
    for i in range(n):
        inds = sorted(range(m), key=lambda x: colsum[x])[:a]
        for j in inds:
            colsum[j] += 1
            ans[i][j] = 1
    print("YES")
    for ai in ans:
        print(*ai)
    return

t = int(input())
for tt in range(1, t + 1):
    n , m , a, b = [int(i) for i in input().split(" ")]
    solve()


def solve():
    if not n*a == m * b:
        print("NO")
        return
    ans = [[0 for _ in range(m)] for _ in range(n)]
    colsum = [0]*m
    for i in range(n):
        inds = sorted(range(m), key=lambda x: colsum[x])[:a]
        for j in inds:
            colsum[j] += 1
            ans[i][j] = 1
    print("YES")
    for ai in ans:
        print(*ai, sep="")
    return

t = int(input())
for tt in range(1, t + 1):
    n , m , a, b = [int(i) for i in input().split(" ")]
    solve()


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    n,m,a,b = map(int,input().split())
    if(n*a != m*b):
        print("NO")
    else:
        print("YES")
        p = "1"*a + "0"*(m-a)
        for i in range(n):
                print(p)
                for j in range(a):
                    p= shift(p)


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    n,m,a,b = map(int,input().split())
    if(n*a != m*b):
        print("NO")
    else:
        print("YES")
        p = "1"*a + "0"*(m-a)
        for i in range(n//b):
            for j in range(b):
                print(p)
            for j in range(a):
                p= shift(p)


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    res = []
    ok = True
    p = "1"*a + "0"*(n-a)
    for i in range(m):
            res.append([i for i in p])
            for j in range(a):
                p= shift(p)
    for i in range(m):
        sumi = sum(int(i) for i in res[i])
        if(sumi!=a):
            ok = False
    for i in range(n):
        sumi = sum(int(res[j][i]) for j in range(m))
        if(sumi!=b):
            ok=False
    if(not ok):
        print("NO")
    else :
        print("YES")
        for i in range(m):
            print("".join(res[i]))


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    res = []
    if(n*a!=m*b):
        print("NO")
        continue
    p = "1"*a + "0"*(n-a)
    for i in range(m//b):
            for j in range(b):
                res.append([i for i in p])
            for j in range(a):
                p= shift(p)
    print("YES")
    for i in range(m):
            print("".join(res[i]))


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    n,m,a,b = map(int,input().split())
    if(n*a != m*b):
        print("NO")
    else:
        print("YES")
        p = "1"*a + "0"*(m-a)
        for i in range(n):
                print(p)
                for k in range(a):
                    p= shift(p)


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    if (n * b != m * a):
        print("NO")
    else:
        print("YES")
        p = "1"*a + "0"*(n-a)
        for i in range(m):
            print(p)
            for z in range(a):
                p= shift(p)


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    if (n * b != m * a):
        print("NO")
    else:
        print("YES")
        p = "1"*a + "0"*(n-a)
        for i in range(m):
            print(p)
            for k in range(a):
                p= shift(p)


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    res = []
    p = "1"*a + "0"*(n-a)
    for i in range(m):
            res.append([i for i in p])
            for j in range(a):
                p= shift(p)
    cnta= 10**9
    cntb = 10**9
    for i in range(m):
        sumi = sum(int(i) for i in res[i])
        cnta = min(cnta,sumi)
    for i in range(n):
        sumi = sum(int(res[j][i]) for j in range(m))
        cntb = min(cntb,sumi)
    if(cnta!=a or cntb!=b):
        print("NO")
    else :
        print("YES")
        for i in range(m):
            print("".join(res[i]))


for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    if (n * b != m * a):
        print("NO")
    else:
        print("YES")
        p = "1"*a + "0"*(n-a)
        for i in range(m):
            print(p)
            p = "".join(p[i] for i in range(n-a,n)) + "".join(p[i] for i in range(n-a))


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    res = []
    p = "1"*a + "0"*(n-a)
    for i in range(round(m/b)):
            res.append([i for i in p])
            for j in range(a):
                p= shift(p)
    cnta= 10**9
    cntb = 10**9
    for i in range(m):
        sumi = sum(int(i) for i in res[i])
        cnta = min(cnta,sumi)
    for i in range(n):
        sumi = sum(int(res[j][i]) for j in range(m))
        cntb = min(cntb,sumi)
    if(cnta!=a or cntb!=b):
        print("NO")
    else :
        print("YES")
        for i in range(m):
            print("".join(res[i]))


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    res = []
    p = "1"*a + "0"*(n-a)
    for i in range(m):
            res.append([i for i in p])
            for j in range(a):
                p= shift(p)
    cnta= 0
    cntb = 0
    for i in range(m):
        sumi = sum(int(i) for i in res[i])
        cnta = max(cnta,sumi)
    for i in range(n):
        sumi = sum(int(res[j][i]) for j in range(m))
        cntb = max(cntb,sumi)
    if(cnta!=a or cntb!=b):
        print("NO")
    else :
        print("YES")
        for i in range(m):
            print("".join(res[i]))


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    res = []
    if(m*a!=n*b):
        print("NO")
        continue
    p = "1"*a + "0"*(n-a)
    for i in range(m//b):
            for j in range(b):
                res.append([i for i in p])
            for j in range(a):
                p= shift(p)
    print("YES")
    for i in range(m):
            print("".join(res[i]))


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    if (n * b != m * a):
        print("NO")
    else:
        print("YES")
        p = "1"*a + "0"*(n-a)
        for i in range(round(m//b)):
            for j in range(b):
                print(p)
            for k in range(a):
                p= shift(p)


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    res = []
    p = "1"*a + "0"*(n-a)
    for i in range(m):
                res.append([i for i in p])
                for j in range(a):
                    p= shift(p)
    cnta= sum(int(res[0][j]) for j in range(n))
    cntb = sum(int(res[i][0]) for i in range(m))
    if(cnta!=a or cntb!=b):
        print("NO")
    else :
        print("YES")
        for i in range(m):
            print("".join(res[i]))


def shift(s):
    s_deq = [i for i in s]
    return "".join(s_deq[-1])+"".join(s_deq[0:len(s)-1])
for _ in range(int(input())):
    m,n,a,b = map(int,input().split())
    res = []
    ok = True
    p = "1"*a + "0"*(n-a)
    for i in range(m):
            res.append([i for i in p])
            for j in range(a):
                p= shift(p)
    if(n*b != m*a):
        print("NO")
    else :
        print("YES")
        for i in range(m):
            print("".join(res[i]))


for _ in range(int(input())):
    n,m,a,b = map(int,input().split())
    c=0
    S=[]
    i=0;f=0
    if(n==m and a!=b):
        print("NO")
        continue
    while(i<n):
        j=0
        while(j<b):
            s ="0"*c+"1"*a+"0"*(m-a-c)
            S.append(s)
            if(len(s)>m):
                f = 1
                break
            j+=1
            i+=1
        if(f==1):
            break
        c+=a
    if(f==1):
        print("NO")
        continue
    print("YES")
    for i in S:
        print(i)
# priyanshu kumar


for _ in range(int(input())):
    n,m,a,b = map(int,input().split())
    c=0
    S=[]
    i=0;f=0
    while(i<n):
        j=0
        while(j<b):
            s ="0"*c+"1"*a+"0"*(m-a-c)
            S.append(s)
            if(len(s)>m):
                f = 1
                break
            j+=1
            i+=1
        if(f==1):
            break
        c+=a
    if(f==1):
        print("NO")
        continue
    print("YES")
    for i in S:
        print(i)
# priyanshu kumar


for _ in range(int(input())):
    n,m,a,b = map(int,input().split())
    c=0
    S=[]
    i=0;f=0
    if(a*n!=b*m or a*n>n*m):
        print("NO")
        continue
    while(i<n):
        j=0
        while(j<b):
            s ="0"*c+"1"*a+"0"*(m-a-c)
            S.append(s)
            if(len(s)>m):
                f = 1
                break
            j+=1
            i+=1
        if(f==1):
            break
        c+=a
    if(f==1):
        print("NO")
        continue
    print("YES")
    for i in S:
        print(i)
# priyanshu kumar


for _ in range(int(input())):
    n,m,a,b = map(int,input().split())
    if(a*n != b*m):
        print("NO")
        continue
    print("YES")
    flag = 0;j = 0
    for i in range(n):
        flag = a
        L = [0]*m
        while(flag>0):
            L[j%m]=1
            flag-=1
            j+=1
        for d in L:
            print(d,end="")
        print()
#  Priyanshu Kumar ------------------ heart within and God overhead


# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 2020/6/4

"""

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def solve(N, M, A, B):
    if N % B != 0 or M % A != 0:
        return False, []

    matrix = [[0 for _ in range(M)] for _ in range(N)]

    cs = 0
    for rs in range(0, N, B):
        if cs + A > M:
            return False, []
        for r in range(rs, rs+B):
            for c in range(cs, cs+A):
                matrix[r][c] = 1
        cs += A

    return True, matrix

T = int(input())
for ti in range(T):
    N, M, A, B = map(int, input().split())
    a, m = solve(N, M, A, B)
    if not a:
        print('NO')
    else:
        print('YES')
        for row in m:
            print(''.join(map(str, row)))


# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 2020/6/4

"""

import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def gcd(x, y):
    while y:
        x, y = y, x%y

    return x

def lcm(a, b):
    c = gcd(a, b)
    return a * b // c

def solve(N, M, A, B):
    if N * A != M * B:
        return False, []

    d = lcm(N, M) // N
    matrix = [[0 for _ in range(M)] for _ in range(N)]
    cs = 0
    for r in range(N):
        for c in range(cs, min(cs+A, M)):
            matrix[r][c] = 1
        for c in range(0, A-(M-cs)):
            matrix[r][c] = 1
        cs = (cs + d) % M

    return True, matrix

T = int(input())
for ti in range(T):
    N, M, A, B = map(int, input().split())
    a, m = solve(N, M, A, B)
    if not a:
        print('NO')
    else:
        print('YES')
        for row in m:
            print(''.join(map(str, row)))


t=int(input())
for you in range(t):
    l=input().split()
    n=int(l[0])
    m=int(l[1])
    a=int(l[2])
    b=int(l[3])
    arr=[[0 for i in range(m)]for i in range(n)]
    if(n*a!=m*b):
        print("NO")
    else:
        diff=m//a
        for i in range(n):
            for j in range(a):
                arr[i][(i+j*diff)%m]=1
        print("YES")
        for i in range(n):
            for j in range(m):
                print(arr[i][j],end="")
            print()


t=int(input())
for you in range(t):
    l=input().split()
    n=int(l[0])
    m=int(l[1])
    a=int(l[2])
    b=int(l[3])
    arr=[[0 for i in range(m)]for i in range(n)]
    if(n*a!=m*b):
        print("NO")
    else:
        diff=1
        for i in range(n):
            for j in range(a):
                arr[i][(i*a+j)%m]=1
        print("YES")
        for i in range(n):
            for j in range(m):
                print(arr[i][j],end="")
            print()


t=int(input())
for you in range(t):
    l=input().split()
    n=int(l[0])
    m=int(l[1])
    a=int(l[2])
    b=int(l[3])
    arr=[[0 for i in range(m)]for i in range(n)]
    if(n*a!=m*b):
        print("NO")
    elif(a>m or b>n):
        print("NO")
    else:
        diff=m//a
        for i in range(n):
            for j in range(a):
                arr[i][(i+j*diff)%m]=1
        print("YES")
        for i in range(n):
            for j in range(m):
                print(arr[i][j],end="")
            print()


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
    return int(stdin.readline().strip())

def get_tuple():
    return map(int, stdin.readline().split())

def get_list():
    return list(map(int, stdin.readline().split()))

def solve():
    n,m,a,b = map(int, input().strip().split())
    matrix = [[0 for _ in range(m)] for _ in range(n)]
    if n*a!=m*b: print("NO")
    else:
        ans = "YES"
        for i in range(n):
            j = i%m
            tempb,tempa = b,a
            f = 0
            while tempa>0 and f!=2:
                    matrix[i][j] = 1
                    tempa -= 1
                    j = (j+1)%m
                    if j==i%m:
                        f += 1
        print(ans)
        if ans=="YES":
            for i in range(n):
                print("".join(str(e) for e in matrix[i]))

def main():
    solve()

TestCases = True

if TestCases:
    for i in range(get_int()):
        main()
else:
    main()


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
    return int(stdin.readline().strip())

def get_tuple():
    return map(int, stdin.readline().split())

def get_list():
    return list(map(int, stdin.readline().split()))

def solve():
    n,m,a,b = map(int, input().strip().split())
    matrix = [[0 for _ in range(m)] for _ in range(n)]
    if n*a!=m*b: print("NO")
    else:
        ans = "YES"
        j = 0
        for i in range(n):
            tempb,tempa = b,a
            f = 0
            while tempa>0 and f!=2:
                    matrix[i][j] = 1
                    tempa -= 1
                    j = (j+1)%m
                    if j==i%m:
                        f += 1
        print(ans)
        if ans=="YES":
            for i in range(n):
                print("".join(str(e) for e in matrix[i]))

def main():
    solve()

TestCases = True

if TestCases:
    for i in range(get_int()):
        main()
else:
    main()


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
    return int(stdin.readline().strip())

def get_tuple():
    return map(int, stdin.readline().split())

def get_list():
    return list(map(int, stdin.readline().split()))

def solve():
    n,m,a,b = map(int, input().strip().split())
    matrix = [[0 for _ in range(m)] for _ in range(n)]
    columns = [0]*m
    ans = "YES"
    for i in range(n):
        j = i%m
        tempb,tempa = b,a
        f = 0
        while tempa>0 and f!=2:
            if columns[j]<b:
                columns[j] += 1
                matrix[i][j] = 1
                tempa -= 1
            j = (j+1)%m
            if j==i%m:
                f += 1
        if tempa>0: ans="NO"
    for val in columns:
        if val!=b:
            ans = "No"
            break
    print(ans)
    if ans=="YES":
        for i in range(n):
            print("".join(str(e) for e in matrix[i]))

def main():
    solve()

TestCases = True

if TestCases:
    for i in range(get_int()):
        main()
else:
    main()


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
    return int(stdin.readline().strip())

def get_tuple():
    return map(int, stdin.readline().split())

def get_list():
    return list(map(int, stdin.readline().split()))

def solve():
    n,m,a,b = map(int, input().strip().split())
    matrix = [[0 for _ in range(m)] for _ in range(n)]
    columns = [0]*m
    ans = "YES"
    for i in range(n):
        j = i%m
        tempb,tempa = b,a
        f = 0
        while tempa>0 and f!=2:
            if columns[j]<b:
                columns[j] += 1
                matrix[i][j] = 1
                tempa -= 1
            j = (j+1)%m
            if j==i%m:
                f += 1
        if tempa>0: ans="NO"
    for val in columns:
        if val!=b:
            ans = "NO"
            break
    print(ans)
    if ans=="YES":
        for i in range(n):
            print("".join(str(e) for e in matrix[i]))

def main():
    solve()

TestCases = True

if TestCases:
    for i in range(get_int()):
        main()
else:
    main()


#include <bits/stdc++.h>
using namespace std;

struct node {
	int pos1;
	int pos2;
	string a;
	string b;
};

stack<int> tryy;
vector<node> catchh;

string throww = "";
int idx;

bool cmp(node x, node y) {
	return x.pos1 < y.pos1;
}

int main() {
	int n;
	cin >> n;
	getchar();
	for(int i = 1; i <= n; ++ i) {
		string s;
		getline(cin, s);

		int len = s.length();

		for(int j = 0; j < len; ++ j) {
			if(s[j] == ' ') continue;
			if(s[j] == 't') {
				if(s[j + 1] == 'r') { // try
					tryy.push(i);
				}
				else { // throw
					int k = j + 1;
					for(; k < len; ++ k) {
						if(s[k] == '(') break;
					}
					++ k;

					for(; k < len; ++ k) {
						if(s[k] != ' ') break;
					}

					for(; k < len; ++ k) {
						if(s[k] == ' ' || s[k] == ')') break;
						throww = throww + s[k];
					}

					idx = i;
				}

				break;
			}
			if(s[j] == 'c') { // catch
				string aa = "";

				int k = j + 1;
				for(; k < len; ++ k) {
					if(s[k] == '(') break;
				}
				++ k;
				for(; k < len; ++ k) {
					if(s[k] != ' ') break;
				}

				for(; k < len; ++ k) {
					if(s[k] == ' ' || s[k] == ',') break;
					aa = aa + s[k];
				}

				string bb = "";

				for(; k < len; ++ k) {
					if(s[k] == '\"') break;
				}
				++ k;

				for(; k < len; ++ k) {
					if(s[k] == '\"') break;
					bb = bb + s[k];
				}

				//cout << i << " " << aa << " " << bb << endl;

				int pos1 = tryy.top();
				tryy.pop();
				catchh.push_back({pos1, i, aa, bb});

				break;
			}
		}
	}

	sort(catchh.begin(), catchh.end(), cmp);

	int siz = catchh.size();

//	cout << "---- catchh :\n" ;
//	for(auto x : catchh) {
//		cout << x.pos1 << " " << x.pos2 << " " << x.a << " " << x.b << endl;
//	}
//
//	cout << "\n\n";
//	cout << "idx :" << idx << endl;

 	bool f = 0;

 	for(int i = siz - 1; i >= 0; -- i) {
 		if(f) break;
 		node tmp = catchh[i];

 		//cout << tmp.pos1 << " " << tmp.pos2 << endl;
 		if(tmp.pos1 < idx && tmp.pos2 > idx) {
 			//cout << throww << " " << tmp.a << endl;
 			//cout << (tmp.a == throww) << endl;
 			if(tmp.a == throww) {
 				cout << tmp.b ;
 				f = 1;
 				break;
			}
		}
	}

	if(!f) {
		cout << "Unhandled Exception";
	}

	return 0;
}


//lxrtxdy!
#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 100010
using namespace std;
int n,cnt;
char s[maxn],st[maxn],tmp[maxn],ch;
int main(){
//	freopen("Cola.txt","r",stdin);
	scanf("%d",&n);
	ch=getchar();
	while(ch!='\n')ch=getchar();
	bool flag=0;
	while(n--){
		int len=0;
		bool key=0;
		ch=getchar();
		while(ch!='\n'){
			if(ch=='"')key=1;
			if(key)s[len++]=ch;
			else if(ch!=' ')s[len++]=ch;
			ch=getchar();
		}
		s[len++]='\0';
		if(flag){
			if(s[1]=='r')cnt++;
			if(s[0]=='c'){
				if(cnt)cnt--;
				else {
					int l=0;
					for(int i=6;s[i]!=',';i++)tmp[l++]=s[i];
					tmp[l++]='\0';
					if(!strcmp(tmp,st)){
						for(int i=5+l+2;s[i]!='"';i++){
							printf("%c",s[i]);
						}
						flag=0;
						puts("");
						return 0;
					}
				}
			}
		}
		else if(s[1]=='h'){
			int l=0;
			for(int i=6;s[i]!=')';i++){
				st[l++]=s[i];
			}
			st[l++]='\0';
			flag=1;
		}
	}
	printf("Unhandled Exception");
	puts("");
	return 0;
}
//orzlxr!


#include<bits/stdc++.h>
#define oo 2000000000
#define ll long long
using namespace std;
struct node
{
    stack<int> ms;
};
stack<int> StackOfTry;
map<string,node> MapOfType;
string str;
int n,m,p,k,len,i;
char s[80];
bool f;
int main()
{
    scanf("%d\n",&m);
    f=true;
	MapOfType.clear();
    for (p=1;p<=m;p++)
    {
        gets(s);
        len=strlen(s);
        for (i=0;i<len;i++)
			if (s[i]!=' ')
				break;
        if (s[i]=='t' && s[i+1]=='r')
        {
            StackOfTry.push(p);
        }
		else
        	if (s[i]=='t')
            {
                i+=5;
                for (;i<len;i++)
                    if (s[i]!='(' && s[i]!=' ')
						break;
                str="";
                for (;i<len && s[i]!=')' && s[i]!=' ';i++)
                    str+=s[i];
                MapOfType[str].ms.push(p);
            }
			else
              	if (s[i]=='c')
              	{
                    k=StackOfTry.top();
                    StackOfTry.pop();
                    i+=5;
                    for (;i<len;i++)
                        if (s[i]!='(' && s[i]!=' ')
							break;
                    str="";
                    for (;i<len && s[i]!=',' && s[i]!=' ';i++)
                        str+=s[i];
                    if (MapOfType.find(str)!=MapOfType.end())
                        if (!MapOfType[str].ms.empty())
                            if (MapOfType[str].ms.top()>k)
                            {
                                f=false;
                                MapOfType[str].ms.pop();
                                for (;i<len;i++)
                                    if (s[i]=='"')
										break;
                                i++;
                                for (;s[i]!='"';i++)
                                    printf("%c",s[i]);
                                printf("\n");
                            }
            	}
    }
    if(f)
		printf("Unhandled Exception\n");
    return 0;
}


// Problemok.cpp: определяет точку входа для консольного приложения.
//

//# include "stdafx.h"

# include <iostream>
# include <string>
# include <complex>
# include <math.h>
# include <set>
# include <vector>
# include <map>
# include <queue>
# include <stdio.h>
# include <stack>
# include <algorithm>
# include <list>
# include <ctime>

# include <memory.h>
# include <assert.h>

using namespace std;

# define exit cin.get(), cin.get()
# define pb push_back
# define ll long long

const ll N = 1e5 + 10;
const ll mod = 1e9 + 7;
const ll INF = 1e18;
const ll inf = -1e18;

ll S[N], tp, idm, l, r, n;
string tm1;

int main()
{
	cin >> n >> ws;
	for (int i = 1; i <= n; i++) {
		string s;
		getline(cin, s);
		for (int j = 0; j < s.size(); j++) {
			if (s[j] == '(' || s[j] == ')' || s[j] == ',') {
				s[j] = ' ';
			}
		}
		istringstream ss(s);
		ss >> s;
		if (s == "try") {
			S[++tp] = i;
		}
		else if (s == "throw") {
				ss >> tm1;
				idm = i;
		}
		else if (s == "catch") {
			string ans;
			ss >> ans;
			if (ans == tm1 && S[tp] < idm) {
					getline(ss, ans);
					string str = "";
					l = ans.find_first_of('\"');
					r = ans.find_last_of('\"');
					str = ans.substr(l + 1, r - l - 1);
					cout << str << '\n';
					exit;
					return 0;
			}
		    S[tp--] = 0;
		}
	}
	cout << "Unhandled Exception";
	exit;
	return 0;
}


#include <bits/stdc++.h>

#define FOR(i,a,b) for(int i=(a),_b=(b); i<=_b; i++)
#define FORD(i,a,b) for(int i=(a),_b=(b); i>=_b; i--)
#define REP(i,a) for(int i=0,_a=(a); i<_a; i++)
#define EACH(it,a) for(__typeof(a.begin()) it = a.begin(); it != a.end(); ++it)

#define DEBUG(x) { cout << #x << " = "; cout << (x) << endl; }
#define PR(a,n) { cout << #a << " = "; FOR(_,1,n) cout << a[_] << ' '; cout << endl; }
#define PR0(a,n) { cout << #a << " = "; REP(_,n) cout << a[_] << ' '; cout << endl; }

#define sqr(x) ((x) * (x))
using namespace std;

string s[100111];
char tmp[100111];

int main() {
    ios :: sync_with_stdio(false);
    int n;
    while (scanf("%d\n", &n) == 1) {
        FOR(i,1,n) {
            gets(tmp);
            s[i] = string(tmp);
        }
        stack< pair<string,string> > st;
        FORD(i,n,1) {
            REP(t,s[i].length()) {
                if (s[i][t] == '(' || s[i][t] == ')' || s[i][t] == ',') s[i][t] = ' ';
            }
            istringstream ss(s[i]);

            string command; ss >> command;
            if (command == "try") {
                st.pop();
            }
            else if (command == "throw") {
                string typ; ss >> typ;
                while (!st.empty() && st.top().first != typ) {
                    st.pop();
                }
                if (st.empty()) puts("Unhandled Exception");
                else puts(st.top().second.c_str());
                break;
            }
            else if (command == "catch") {
                string typ; ss >> typ;
                string msg = "";
                bool need = false;
                REP(t,s[i].length()) {
                    if (s[i][t] == '"') need = !need;
                    else {
                        if (need) msg += s[i][t];
                    }
                }
                st.push(make_pair(typ, msg));
            }
        }
    }
    return 0;
}


#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
char s[90],r[90],a[90],b[90],ans[90]={"Unhandled Exception"};
int n;
bool done=0;
bool check(){
    bool hv=0;
    while(scanf("%*[^a-z]%[a-z]",s),s[1]!='a'){
        if(s[1]=='r') hv|=check();
        if(s[1]=='h')scanf("%*[^A-Za-z]%[A-Za-z]",r),hv=true;
    }
    scanf("%*[^A-Za-z]%[A-Za-z]",a),scanf("%*[^\"]\"%[^\"]",b);
    if(hv&&!done&&strcmp(a,r)==0)done=true,strcpy(ans,b);
    return hv;
}
int main(){
    scanf("%d",&n);
    while(scanf("%*[^a-z]%[a-z]",s)!=EOF&&s[1]=='r')check();
    scanf("%*[^\n]\n");
    printf("%s\n",ans);
    return 0;
}


#include <bits/stdc++.h>

typedef long long ll;
using namespace std;

#define all(x) x.begin(), x.end()
#define f(i,a,b) for(int i = (a); i <= (b); i++)
#define fd(i,a,b) for(int i = (a); i >= (b); i--)
#define mp make_pair
#define faster_io() ios_base::sync_with_stdio(false)
#define pb push_back
#define pii pair<int,int>
#define SZ(x) ((int)x.size())
#define vii vector<pair<int,int>>

const int INF = 1000000002;
const ll INFLL = 100000000000000000ll;
const ll MOD = 1000000007;

// ----------------------------------------------------------------------------------------------------------

int N;
map<string,int> M;

vector<string> parse(string s)
{
    int n = SZ(s), pos = 0, type = 0;
    vector<string> ret;

    f(i,0,n-1)
    {
        if(s[i] != '.')
        {
            if(s[i+1] == 'r')
            {
                return {"try"};
            }
            if(s[i+1] == 'a')
            {
                ret.pb("catch");
                type = 1;
                pos = i+5;
                break;
            }
            if(s[i+1] == 'h')
            {
                ret.pb("throw");
                type = 2;
                pos = i+5;
                break;
            }
        }
    }

    if(type == 1)
    {
        int nx = 0;

        f(i,pos,n-1)
        {
            if(s[i] == '(')
            {
                bool found = false;
                string exc = "";

                f(i2,i+1,n-1)
                {
                    if((s[i2] >= 'a' && s[i2] <= 'z') || (s[i2] >= 'A' && s[i2] <= 'Z')) exc += s[i2], found = true;
                    else if(found)
                    {
                        nx = i2+1;
                        break;
                    }
                }

                ret.pb(exc);
                break;
            }
        }

        bool found = false;
        string msg = "";

        f(i,nx,n-1)
        {
            if(s[i] == '"')
            {
                if(found) break;
                found = true;
            }
            else if(found) msg += s[i];
        }

        ret.pb(msg);
    }
    else
    {
        f(i,pos,n-1) if(s[i] == '(')
        {
            bool found = false;
            string exc = "";

            f(i2,i+1,n-1)
            {
                if((s[i2] >= 'a' && s[i2] <= 'z') || (s[i2] >= 'A' && s[i2] <= 'Z')) exc += s[i2], found = true;
                else if(found) break;
            }

            ret.pb(exc);
            break;
        }
    }

    return ret;
}

int main()
{
    cin >> N;
    string s;
    getline(cin,s);
    stack<int> open;
    bool print = false;
    f(i,1,N)
    {
        getline(cin,s);
        vector<string> v = parse(s);
        if(v.empty()) continue;
        if(v[0] == "try")
        {
            open.push(i);
        }
        else if(v[0] == "throw") M[v[1]] = i;
        else
        {
            int l = open.top();
            open.pop();
            if(M[v[1]] > l)
            {
                cout << v[2] << "\n";
                M[v[1]] = 0;
                print = true;
            }
        }
    }
    if(!print) cout << "Unhandled Exception";
}


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <queue>
#include <tuple>
#include <map>
#include <stack>
#include <set>
#include <deque>
#include <functional>
#include <sstream>
using namespace std;

// ������ ll �̻��� ��� INF�� 98765432100000 �������� ũ�� �ؾ���
// �Է¹޴� ���� 10^9 �̰� ���� ���� �װ͵��� ���ϴ� �����̶�� ���� ll �ϼ� �ִ�
// priority_queue �� �⺻������ �������� �����̴�. ������������ �ϰ� �ʹٸ� priority_queue<int, vector<int>, greater<int>>
// queue���� pop�ϱ� ������ �ݵ�� empty�� ��츦 üũ�ϰ� ����ó�� �����

#define INF 9876543210
#define mod 1000000007
#define mt make_tuple
#define mp make_pair
typedef long long ll;

int n, pos, parent;
tuple<string, string, int> tree[1000000];
int start;

stack<tuple<string, string, int>> st;

int main() {

	char str[101];
	pos = 1;

	scanf("%d", &n);

	string ans;
	bool ok = false;
	bool isMeetThrow = false;
	string throwName;
	int tryCnt = 0;
	fgets(str, 100, stdin);

	for (int i = 0; i < n; i++) {
		fgets(str, 100, stdin);

		if (ok) continue;

		int length = strlen(str);
		for (int j = 0; j < length-1; j++) {
			if (str[j] == 't' && str[j+1] == 'r') {
				if (isMeetThrow) {
					tryCnt++;
				}
				break;
			}
			if (str[j] == 't' && str[j + 1] == 'h') {
				isMeetThrow = true;
				int cur = j;
				while (str[cur] != '(') {
					cur++;
				}
				cur++;
				while (str[cur] == ' ') {
					cur++;
				}
				string s1, s2;
				while (str[cur] != ' ' && str[cur] != ')') {
					throwName.push_back(str[cur]);
					cur++;
				}
				break;
			}
			if (str[j] == 'c') {

				parent--;
				int cur = j;
				while (str[cur] != '(') {
					cur++;
				}
				cur++;
				while (str[cur] == ' ') {
					cur++;
				}
				string s1, s2;
				while (str[cur] != ',') {
					s1.push_back(str[cur]);
					cur++;
				}
				while (str[cur] != '\"') {
					cur++;
				}
				cur++;
				while (str[cur] != '\"') {
					s2.push_back(str[cur]);
					cur++;
				}
				if (isMeetThrow && tryCnt == 0) {
					if (s1.compare(throwName) == 0) {
						ans = s2;
						ok = true;
					}
				}
				if (isMeetThrow && tryCnt > 0) {
					tryCnt--;
				}
				break;
			}
		}
	}
	if (ok) {
		printf("%s\n", ans.c_str());
	}
	else {
		printf("Unhandled Exception\n");
	}

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <queue>
#include <tuple>
#include <map>
#include <stack>
#include <set>
#include <deque>
#include <functional>
#include <sstream>
using namespace std;

// ������ ll �̻��� ��� INF�� 98765432100000 �������� ũ�� �ؾ���
// �Է¹޴� ���� 10^9 �̰� ���� ���� �װ͵��� ���ϴ� �����̶�� ���� ll �ϼ� �ִ�
// priority_queue �� �⺻������ �������� �����̴�. ������������ �ϰ� �ʹٸ� priority_queue<int, vector<int>, greater<int>>
// queue���� pop�ϱ� ������ �ݵ�� empty�� ��츦 üũ�ϰ� ����ó�� �����

#define INF 9876543210
#define mod 1000000007
#define mt make_tuple
#define mp make_pair
typedef long long ll;

int n, pos, parent;
tuple<string, string, int> tree[1000000];
int start;

stack<tuple<string, string, int>> st;

int main() {

	char str[101];
	pos = 1;

	scanf("%d", &n);

	string ans;
	bool ok = false;
	bool isMeetThrow = false;
	string throwName;
	int tryCnt = 0;
	fgets(str, 100, stdin);

	for (int i = 0; i < n; i++) {
		fgets(str, 100, stdin);

		if (ok) continue;

		int length = strlen(str);
		for (int j = 0; j < length-1; j++) {
			if (str[j] == 't' && str[j+1] == 'r') {
				if (isMeetThrow) {
					tryCnt++;
				}
				break;
			}
			if (str[j] == 't' && str[j + 1] == 'h') {
				isMeetThrow = true;
				int cur = j;
				while (str[cur] != '(') {
					cur++;
				}
				cur++;
				while (str[cur] == ' ') {
					cur++;
				}
				string s1, s2;
				while (str[cur] != ' ') {
					throwName.push_back(str[cur]);
					cur++;
				}
				tryCnt = 1;
				break;
			}
			if (str[j] == 'c') {
				parent--;
				int cur = j;
				while (str[cur] != '(') {
					cur++;
				}
				cur++;
				while (str[cur] == ' ') {
					cur++;
				}
				string s1, s2;
				while (str[cur] != ',') {
					s1.push_back(str[cur]);
					cur++;
				}
				while (str[cur] != '\"') {
					cur++;
				}
				cur++;
				while (str[cur] != '\"') {
					s2.push_back(str[cur]);
					cur++;
				}
				if (isMeetThrow && tryCnt == 0) {
					if (s1.compare(throwName) == 0) {
						ans = s2;
						ok = true;
					}
				}
				tryCnt--;
				break;
			}
		}
	}
	if (ok) {
		printf("%s\n", ans.c_str());
	}
	else {
		printf("Unhandled Exception\n");
	}

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <queue>
#include <tuple>
#include <map>
#include <stack>
#include <set>
#include <deque>
#include <functional>
#include <sstream>
using namespace std;

// ������ ll �̻��� ��� INF�� 98765432100000 �������� ũ�� �ؾ���
// �Է¹޴� ���� 10^9 �̰� ���� ���� �װ͵��� ���ϴ� �����̶�� ���� ll �ϼ� �ִ�
// priority_queue �� �⺻������ �������� �����̴�. ������������ �ϰ� �ʹٸ� priority_queue<int, vector<int>, greater<int>>
// queue���� pop�ϱ� ������ �ݵ�� empty�� ��츦 üũ�ϰ� ����ó�� �����

#define INF 9876543210
#define mod 1000000007
#define mt make_tuple
#define mp make_pair
typedef long long ll;

int n, pos, parent;
tuple<string, string, int> tree[1000000];
int start;

stack<tuple<string, string, int>> st;

int main() {

	char str[101];
	pos = 1;

	scanf("%d", &n);

	string ans;
	bool ok = false;
	bool isMeetThrow = false;
	string throwName;
	int tryCnt = 0;
	fgets(str, 100, stdin);

	for (int i = 0; i < n; i++) {
		fgets(str, 100, stdin);

		if (ok) continue;

		int length = strlen(str);
		for (int j = 0; j < length-1; j++) {
			if (str[j] == 't' && str[j+1] == 'r') {
				if (isMeetThrow) {
					tryCnt++;
				}
				break;
			}
			if (str[j] == 't' && str[j + 1] == 'h') {
				isMeetThrow = true;
				int cur = j;
				while (str[cur] != '(') {
					cur++;
				}
				cur++;
				while (str[cur] == ' ') {
					cur++;
				}
				string s1, s2;
				while (str[cur] != ' ') {
					throwName.push_back(str[cur]);
					cur++;
				}
				break;
			}
			if (str[j] == 'c') {

				parent--;
				int cur = j;
				while (str[cur] != '(') {
					cur++;
				}
				cur++;
				while (str[cur] == ' ') {
					cur++;
				}
				string s1, s2;
				while (str[cur] != ',') {
					s1.push_back(str[cur]);
					cur++;
				}
				while (str[cur] != '\"') {
					cur++;
				}
				cur++;
				while (str[cur] != '\"') {
					s2.push_back(str[cur]);
					cur++;
				}
				if (isMeetThrow && tryCnt == 0) {
					if (s1.compare(throwName) == 0) {
						ans = s2;
						ok = true;
					}
				}
				if (isMeetThrow && tryCnt > 0) {
					tryCnt--;
				}
				break;
			}
		}
	}
	if (ok) {
		printf("%s\n", ans.c_str());
	}
	else {
		printf("Unhandled Exception\n");
	}

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <queue>
#include <tuple>
#include <map>
#include <stack>
#include <set>
#include <deque>
#include <functional>
#include <sstream>
using namespace std;

// ������ ll �̻��� ��� INF�� 98765432100000 �������� ũ�� �ؾ���
// �Է¹޴� ���� 10^9 �̰� ���� ���� �װ͵��� ���ϴ� �����̶�� ���� ll �ϼ� �ִ�
// priority_queue �� �⺻������ �������� �����̴�. ������������ �ϰ� �ʹٸ� priority_queue<int, vector<int>, greater<int>>
// queue���� pop�ϱ� ������ �ݵ�� empty�� ��츦 üũ�ϰ� ����ó�� �����

#define INF 9876543210
#define mod 1000000007
#define mt make_tuple
#define mp make_pair
typedef long long ll;

int n, pos, parent;
tuple<string, string, int> tree[1000000];
int start;

stack<tuple<string, string, int>> st;

int main() {

	char str[101];
	pos = 1;

	scanf("%d", &n);

	string ans;
	bool ok = false;
	bool isMeetThrow = false;
	string throwName;
	int tryCnt = 0;
	fgets(str, 100, stdin);

	for (int i = 0; i < n; i++) {
		fgets(str, 100, stdin);

		if (ok) continue;

		int length = strlen(str);
		for (int j = 0; j < length-1; j++) {
			if (str[j] == 't' && str[j+1] == 'r') {
				if (isMeetThrow) {
					tryCnt++;
				}
				break;
			}
			if (str[j] == 't' && str[j + 1] == 'h') {
				isMeetThrow = true;
				int cur = j;
				while (str[cur] != '(') {
					cur++;
				}
				cur++;
				while (str[cur] == ' ') {
					cur++;
				}
				string s1, s2;
				while (str[cur] != ' ' && str[cur] != ')') {
					throwName.push_back(str[cur]);
					cur++;
				}
				break;
			}
			if (str[j] == 'c') {

				parent--;
				int cur = j;
				while (str[cur] != '(') {
					cur++;
				}
				cur++;
				while (str[cur] == ' ') {
					cur++;
				}
				string s1, s2;
				while (str[cur] != ',' && str[cur] != ' ') {
					s1.push_back(str[cur]);
					cur++;
				}
				while (str[cur] != '\"') {
					cur++;
				}
				cur++;
				while (str[cur] != '\"') {
					s2.push_back(str[cur]);
					cur++;
				}
				if (isMeetThrow && tryCnt == 0) {
					if (s1.compare(throwName) == 0) {
						ans = s2;
						ok = true;
					}
				}
				if (isMeetThrow && tryCnt > 0) {
					tryCnt--;
				}
				break;
			}
		}
	}
	if (ok) {
		printf("%s\n", ans.c_str());
	}
	else {
		printf("Unhandled Exception\n");
	}

	return 0;
}


#include <bits/stdc++.h>
using namespace std;

const int maxn = 100005;

bool output;
int n;

void input()
{
    cin >> n;
}

int gettype(char *s)
{
    int cn = 1;
    while (s[cn] && s[cn] < 'a' || s[cn] > 'z') cn ++;
    if (s[cn] == 't' && s[cn + 1] == 'r') return 1;
    if (s[cn] == 't' && s[cn + 1] == 'h') return 2;
    if (s[cn] == 'c') return 3;
    return 0;
}

string getname(char *s)
{
    string re;
    int cn = 1;
    while (s[cn] && s[cn] != '(') cn ++;
    cn ++;
    while (s[cn] && s[cn] == ' ') cn ++;
    while (s[cn] && s[cn] != ' ' && s[cn] != ')') re += s[cn], cn ++;
    return re;
}

string getname2(char *s)
{
    string re;
    int cn = 1;
    while (s[cn] && s[cn] != '(') cn ++;
    cn ++;
    while (s[cn] && s[cn] == ' ') cn ++;
    while (s[cn] && s[cn] != ' ' && s[cn] != ',') re += s[cn], cn ++;
    return re;
}

void prt(char *s)
{
    int cn = 1;
    while (s[cn] != '"') cn ++;
    cn ++;
    while (s[cn] != '"') putchar(s[cn]), cn ++;
}

void solve()
{
    char str[105];
    string varname, cnname;
    int type, st_now = 0, var_dep = -1;
    bool now;
    scanf("\n");
    while (n --) {
        memset(str, 0, sizeof(str));
        gets(str + 1);
        type = gettype(str);
        if (type == 1) { // try
            st_now ++;
            now = false;
        } else if (type == 2) { // throw
            varname = getname(str);
            var_dep = st_now;
            now = true;
        } else if (type == 3) { // catch
            cnname = getname2(str);
            if (cnname == varname && now) {
                prt(str + 1);
                output = true;
                break;
            }
            if (var_dep == st_now && var_dep != -1) now = true;
            if (st_now < var_dep) var_dep = st_now;
            st_now --;
        }
    }
    if (!output) puts("Unhandled Exception");
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    input();
    solve();

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

const int maxn = 100005;

bool output;
int n;
map<string, int> vars, cntime;

void input()
{
    cin >> n;
}

int gettype(char *s)
{
    int cn = 1;
    while (s[cn] < 'a' || s[cn] > 'z') cn ++;
    if (s[cn] == 't' && s[cn + 1] == 'r') return 1;
    if (s[cn] == 't' && s[cn + 1] == 'h') return 2;
    return 3;
}

string getname(char *s)
{
    string re;
    int cn = 1;
    while (s[cn] != '(') cn ++;
    cn ++;
    while (s[cn] == ' ') cn ++;
    while (s[cn] != ' ' && s[cn] != ')') re += s[cn], cn ++;
    return re;
}

string getname2(char *s)
{
    string re;
    int cn = 1;
    while (s[cn] != '(') cn ++;
    cn ++;
    while (s[cn] == ' ') cn ++;
    while (s[cn] != ' ' && s[cn] != ',') re += s[cn], cn ++;
    return re;
}

void prt(char *s)
{
    int cn = 1;
    while (s[cn] != '"') cn ++;
    cn ++;
    while (s[cn] != '"') putchar(s[cn]), cn ++;
}

void solve()
{
    char str[105];
    string varname;
    int type, st_now = 0, cnt = 0;
    while (n --) {
        scanf("\n");
        gets(str + 1);
        type = gettype(str);
        if (type == 1) { // try
            st_now ++;
            cnt ++;
        } else if (type == 2) { // throw
            varname = getname(str);
            vars[varname] = st_now;
            cntime[varname] = cnt;
        } else { // catch
            varname = getname2(str);
            if (vars.count(varname) && (vars[varname] > st_now || (vars[varname] == st_now && cntime[varname] == cnt))) {
                prt(str);
                vars.erase(varname);
                output = true;
            }
            st_now --;
        }
    }
    if (!output) puts("Unhandled Exception");
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    input();
    solve();

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;

}


#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<map>
#include<cmath>
#include<queue>
#include<stack>
#define oo 2000000000
#define ll long long
using namespace std;
struct node
{
       stack<int> ms;
};
stack<int> StackOfTry;
map<string,node> MapOfType;
string str;
int n,m,p,k,len,i;
char s[80];
bool f;
int main()
{
       scanf("%d\n",&m);
       f=true;
       MapOfType.clear();
       for (p=1;p<=m;p++)
       {
              gets(s);
              len=strlen(s);
              for (i=0;i<len;i++)  if (s[i]!=' ') break;
              if (s[i]=='t' && s[i+1]=='r')
              {
                      StackOfTry.push(p);
              }else
              if (s[i]=='t')
              {
                      i+=5;
                      for (;i<len;i++)
                         if (s[i]!='(' && s[i]!=' ') break;
                      str="";
                      for (;i<len && s[i]!=')' && s[i]!=' ';i++)
                         str+=s[i];
                      MapOfType[str].ms.push(p);
              }else
              if (s[i]=='c')
              {
                      k=StackOfTry.top();
                      StackOfTry.pop();
                      i+=5;
                      for (;i<len;i++)
                         if (s[i]!='(' && s[i]!=' ') break;
                      str="";
                      for (;i<len && s[i]!=',' && s[i]!=' ';i++)
                         str+=s[i];
                      if (MapOfType.find(str)!=MapOfType.end())
                         if (!MapOfType[str].ms.empty())
                             if (MapOfType[str].ms.top()>k)
                             {
                                   f=false;
                                   MapOfType[str].ms.pop();
                                   for (;i<len;i++)
                                       if (s[i]=='"') break;
                                   i++;
                                   for (;s[i]!='"';i++)
                                       printf("%c",s[i]);
                                   printf("\n");
                             }
              }
       }
       if (f) printf("Unhandled Exception\n");
       return 0;
}


#include <algorithm>
#include <iostream>
#include <iomanip>
#include <set>
#include <map>
#include <vector>
#include <string>
#include <memory>
#include <cstring>
#include <deque>
#include <cmath>
#include <cassert>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <numeric>
#include <valarray>

#define ll long long
#define ull unsigned long long
#define lld long double

using namespace std;

const ll MAX_NUM = numeric_limits<ll>::max();

vector<string> parseToken(const string& raw) {
    vector<string> res;
    ll tryPos = raw.find("try");
    ll throwPos = raw.find("throw");
    ll catchPos = raw.find("catch");

    if (tryPos == -1) {
        tryPos = MAX_NUM;
    }
    if (throwPos == -1) {
        throwPos = MAX_NUM;
    }
    if (catchPos == -1) {
        catchPos = MAX_NUM;
    }

    if (tryPos != MAX_NUM && tryPos < throwPos && tryPos < catchPos) {
        res.push_back("try");
    }

    if (throwPos != MAX_NUM && throwPos < tryPos && throwPos < catchPos) {
        res.push_back("throw");
        bool insideBr = false;
        string excType;
        for (ll i = throwPos+5; i < raw.size(); ++i) {
            if (raw[i] == '(') {
                insideBr = true;
            }
            if (raw[i] == ')') {
                insideBr = false;
            }
            if (insideBr && isalpha(raw[i])) {
                excType += raw[i];
            }
        }
        res.push_back(excType);
        return res;
    }
    if (catchPos != MAX_NUM && catchPos < tryPos && catchPos < throwPos) {
        res.push_back("catch");
        bool insideBr = false;
        bool insideStr = false;
        string excType;
        string excStr;
        for (ll i = catchPos + 5; i < raw.size(); ++i) {
            if (raw[i] == '(' && !insideStr) {
                insideBr = true;
            }
            if (raw[i] == ')' && !insideStr) {
                insideBr = false;
            }
            if (insideBr && isalpha(raw[i]) && !insideStr) {
                excType += raw[i];
            }
            if (insideBr && !insideStr && raw[i] == '"') {
                insideStr = true;
            } else if (insideBr && insideStr && raw[i] == '"') {
                insideStr = false;
            }
            if (insideStr && raw[i] != '"') {
                excStr += raw[i];
            }
        }
        res.push_back(excType);
        res.push_back(excStr);
    }
    return res;
}

void solve() {
    ll n;
    vector<vector<string>> tokens;
    string tmp;
    getline(cin, tmp);
    n = stoi(tmp);

    for (ll i = 0; i < n; ++i) {
        string s;
        //cin >> s;
        getline(cin, s);
        //cout << "check string: " << s << "\n";
        auto token = parseToken(s);
        if (token.size() > 0) {
            tokens.push_back(token);
        }
    }

    ll depth = 0;
    unordered_map<ll, ll> levelStarts;
    string unrollType;
    ll unrollDepth = 0;
    ll unrollPos = 0;
    for (ll i = 0; i < tokens.size(); ++i) {
        const auto& t = tokens[i];
        if (t[0] == "try") {
            depth += 1;
            levelStarts[depth] = i;
        }
        if (t[0] == "throw" && unrollType.empty()) {
            unrollType = t[1];
            unrollDepth = depth;
            unrollPos = i;
        }
        if (t[0] == "catch") {
            if (!unrollType.empty() && depth <= unrollDepth && unrollType == t[1] && levelStarts[depth] < unrollPos) {
                cout << t[2] << "\n";
                unrollType = "";
            }
            depth -= 1;
        }
    }

    if (!unrollType.empty()) {
        cout << "Unhandled Exception" << endl;
    }

}

/* ================================================================== */

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout << setprecision (numeric_limits<lld>::digits10 + 1);

    int n = 1;
    //cin >> n; // раскоментить если много запросов
    for (ll i = 0; i < n; ++i) {
        solve();
    }

    return 0;
}
//hellobig_tq


#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <utility>
#include <string.h>
#include <map>
#include <stack>
#include <iomanip>
#include <chrono>
#include <random>
#include <bitset>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <fstream>
#define rnd mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define all(x) x.begin(),x.end()
#define PII pair <int,int>
#define N 200005
#define MOD 1000000007
#define INF 1000000000000000000
using namespace std;

int main()
{
	int n;
	cin >> n;
	getchar();
	string line, search;
	stack <int> timestamp;
	int cp = 0, id;
	for (int i = 0; i < n; ++i)
	{
		getline(cin, line);
		replace(all(line), '(', ' ');
		replace(all(line), ')', ' ');
		replace(all(line), ',', ' ');
		istringstream toks(line);

		string cmd, excp, msg;
		toks >> cmd;
		if(cmd == "throw")
		{
			cp = i;
			toks >> search;
		}
		if(cmd == "try")
		{
			timestamp.push(i);
		}
		if(cmd == "catch")
		{
			id = timestamp.top();
			timestamp.pop();
			if(id < cp)
			{
				toks >> excp;
				if(excp == search)
				{
					string msg;
					getline(toks, msg);
					msg.erase(0, msg.find('"') + 1);
					msg.erase(msg.find('"'), msg.size());
					cout << msg << "\n";
					return 0;
				}
			}
		}
	}
	cout << "Unhandled Exception";
}


#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <utility>
#include <string.h>
#include <map>
#include <stack>
#include <iomanip>
#include <chrono>
#include <random>
#include <bitset>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#define rnd mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define all(x) x.begin(),x.end()
#define PII pair <int,int>
#define N 200005
#define MOD 1000000007
#define INF 1000000000000000000
using namespace std;

string s[100005];
int n;
int trailing(string s)
{
	int cnt = 0;
	for (int i = 0; i < (int) s.size(); ++i)
	{
		if(s[i] != ' ')
			return cnt;
		cnt++;
	}
}
void printstat(string s)
{
	int pos;
	for (int i = 0; i < s.size(); ++i)
	{
		if(s[i] == '\"')
		{
			pos = i;
			break;
		}
	}
	for (int i = pos + 1; i < s.size(); ++i)
	{
		if(s[i] == '\"')
		{
			break;
		}
		cout << s[i];
	}

}
void start(int p, int pos, string t)
{
	p = p - 4;
	int found;
	for (int i = pos; i < n; ++i)
	{
		found = s[i].find("catch");
		if(found != string::npos && trailing(s[i]) == p)
		{
			found = s[i].find(t);
			if(found != string::npos)
			{
				printstat(s[i]);
				return;
			}
			p = p - 4;
		}
	}
	cout << "Unhandled Exception";
}
int main()
{
	cin >> n;
	getchar();
	for (int i = 0; i < n; ++i)
	{
		getline(cin, s[i]);
	}
	for (int i = 0; i < n; ++i)
	{
		int found = s[i].find("throw");
		if(found != string::npos)
		{
			string t;
			for (int j = found + 8; s[i][j] != ' '; ++j)
			{
				t.push_back(s[i][j]);
			}
			start(found, i, t);
		}
	}
}


#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <utility>
#include <string.h>
#include <map>
#include <stack>
#include <iomanip>
#include <chrono>
#include <random>
#include <bitset>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#define rnd mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define all(x) x.begin(),x.end()
#define PII pair <int,int>
#define N 200005
#define MOD 1000000007
#define INF 1000000000000000000
using namespace std;

string s[100005];
int n;
int trailing(string s)
{
	int cnt = 0;
	for (int i = 0; i < (int) s.size(); ++i)
	{
		if(s[i] != ' ')
			return cnt;
		cnt++;
	}
}
void printstat(string s)
{
	int pos;
	for (int i = 0; i < s.size(); ++i)
	{
		if(s[i] == '\"')
		{
			pos = i;
			break;
		}
	}
	for (int i = pos + 1; i < s.size(); ++i)
	{
		if(s[i] == '\"')
		{
			break;
		}
		cout << s[i];
	}

}
void start(int p, int pos, string t)
{
	int found1, found2;
	for (int i = pos; i < n; ++i)
	{
		found1 = s[i - 1].find("try");
		found2 = s[i].find("catch");
		// cerr << found1 << " " << found2 << "\n";
		if(found1 == string::npos && found2 != string::npos)
		{
			found1 = s[i].find(t);
			if(found1 != string::npos)
			{
				printstat(s[i]);
				return;
			}
		}
	}
	cout << "Unhandled Exception";
}
int main()
{
	cin >> n;
	getchar();
	for (int i = 0; i < n; ++i)
	{
		getline(cin, s[i]);
	}
	for (int i = 0; i < n; ++i)
	{
		int found = s[i].find("throw");
		if(found != string::npos)
		{
			string t, str;
			str = s[i];
			str.erase(remove(str.begin(), str.end(), ' '), str.end());
			for (int j = found + 6; s[i][j] != ')'; ++j)
			{
				t.push_back(s[i][j]);
			}
			start(found, i + 1, t);
		}
	}
}


#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <utility>
#include <string.h>
#include <map>
#include <stack>
#include <iomanip>
#include <chrono>
#include <random>
#include <bitset>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#define rnd mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define all(x) x.begin(),x.end()
#define PII pair <int,int>
#define N 200005
#define MOD 1000000007
#define INF 1000000000000000000
using namespace std;

int main()
{
	int n;
	cin >> n;
	getchar();
	string line, search;
	stack <int> timestamp;
	int cp = 0, id;
	for (int i = 0; i < n; ++i)
	{
		getline(cin, line);
		replace(all(line), '(', ' ');
		replace(all(line), ')', ' ');
		replace(all(line), ',', ' ');
		istringstream toks(line);

		string cmd, excp, msg;
		toks >> cmd;
		if(cmd == "throw")
		{
			cp = i;
			toks >> search;
			cerr << search << "\n";
		}
		if(cmd == "try")
		{
			timestamp.push(i);
		}
		if(cmd == "catch")
		{
			id = timestamp.top();
			timestamp.pop();
			if(id < cp)
			{
				toks >> excp;
				if(excp == search)
				{
					string msg;
					getline(toks, msg);
					msg.erase(0, msg.find('"') + 1);
					msg.erase(msg.find('"'), msg.size());
					cout << msg << "\n";
					return 0;
				}
			}
		}
	}
	cout << "Unhandled Exception";
}


#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <utility>
#include <string.h>
#include <map>
#include <stack>
#include <iomanip>
#include <chrono>
#include <random>
#include <bitset>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <sstream>
#define rnd mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define all(x) x.begin(),x.end()
#define PII pair <int,int>
#define N 200005
#define MOD 1000000007
#define INF 1000000000000000000
using namespace std;

int main()
{
	int n;
	cin >> n;
	getchar();
	string line, search;
	stack <int> timestamp;
	int cp = 0, id;
	for (int i = 0; i < n; ++i)
	{
		getline(cin, line);
		replace(all(line), '(', ' ');
		replace(all(line), ')', ' ');
		replace(all(line), ',', ' ');
		stringstream toks(line);

		string cmd, excp, msg;
		toks >> cmd;
		if(cmd == "throw")
		{
			cp = i;
			toks >> search;
		}
		if(cmd == "try")
		{
			timestamp.push(i);
		}
		if(cmd == "catch")
		{
			id = timestamp.top();
			timestamp.pop();
			if(id < cp)
			{
				toks >> excp;
				if(excp == search)
				{
					string msg;
					getline(toks, msg);
					msg.erase(0, msg.find('"') + 1);
					msg.erase(msg.find('"'), msg.size());
					cout << msg << "\n";
					return 0;
				}
			}
		}
	}
	cout << "Unhandled Exception";
}


#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <utility>
#include <string.h>
#include <map>
#include <stack>
#include <iomanip>
#include <chrono>
#include <random>
#include <bitset>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#define rnd mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define all(x) x.begin(),x.end()
#define PII pair <int,int>
#define N 200005
#define MOD 1000000007
#define INF 1000000000000000000
using namespace std;

string s[100005];
int n;
int trailing(string s)
{
	int cnt = 0;
	for (int i = 0; i < (int) s.size(); ++i)
	{
		if(s[i] != ' ')
			return cnt;
		cnt++;
	}
}
void printstat(string s)
{
	int pos;
	for (int i = 0; i < s.size(); ++i)
	{
		if(s[i] == '\"')
		{
			pos = i;
			break;
		}
	}
	for (int i = pos + 1; i < s.size(); ++i)
	{
		if(s[i] == '\"')
		{
			break;
		}
		cout << s[i];
	}

}
void start(int p, int pos, string t)
{
	int found1, found2;
	for (int i = pos; i < n; ++i)
	{
		found1 = s[i - 1].find("try");
		found2 = s[i].find("catch");
		// cerr << found1 << " " << found2 << "\n";
		if(found1 == string::npos && found2 != string::npos)
		{
			found1 = s[i].find(t);
			if(found1 != string::npos)
			{
				printstat(s[i]);
				return;
			}
		}
	}
	cout << "Unhandled Exception";
}
int main()
{
	cin >> n;
	getchar();
	for (int i = 0; i < n; ++i)
	{
		getline(cin, s[i]);
	}
	for (int i = 0; i < n; ++i)
	{
		int found = s[i].find("throw");
		if(found != string::npos)
		{
			string t, str;
			str = s[i];
			str.erase(remove(str.begin(), str.end(), ' '), str.end());
			for (int j = 6; str[j] != ')'; ++j)
			{
				t.push_back(str[j]);
			}
			start(found, i + 1, t);
		}
	}
}


#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <utility>
#include <string.h>
#include <map>
#include <stack>
#include <iomanip>
#include <chrono>
#include <random>
#include <bitset>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <fstream>
#define rnd mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define FIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define all(x) x.begin(),x.end()
#define PII pair <int,int>
#define N 200005
#define MOD 1000000007
#define INF 1000000000000000000
using namespace std;

int main()
{
	int n;
	cin >> n;
	getchar();
	string line, search;
	stack <int> timestamp;
	int cp = 0, id;
	for (int i = 0; i < n; ++i)
	{
		getline(cin, line);
		replace(all(line), '(', ' ');
		replace(all(line), ')', ' ');
		replace(all(line), ',', ' ');
		stringstream toks(line);

		string cmd, excp, msg;
		toks >> cmd;
		if(cmd == "throw")
		{
			cp = i;
			toks >> search;
		}
		if(cmd == "try")
		{
			timestamp.push(i);
		}
		if(cmd == "catch")
		{
			id = timestamp.top();
			timestamp.pop();
			if(id < cp)
			{
				toks >> excp;
				if(excp == search)
				{
					string msg;
					getline(toks, msg);
					msg.erase(0, msg.find('"') + 1);
					msg.erase(msg.find('"'), msg.size());
					cout << msg << "\n";
					return 0;
				}
			}
		}
	}
	cout << "Unhandled Exception";
}


#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<map>
using namespace std;
char book[1100];
int cnt=0;
int main()
{
	int n;
	scanf("%d",&n);
	getchar();
	map<string,string> ma;
	char s[1100],st[1100],cn=0;
	int f=0,num=0,t=0,ff=0;
	while(n--)
	{
		cn=0;
		gets(st);
		int flag=0;
		for(int i=0;st[i];i++)
		{
			if(st[i]==' '&&flag==0) continue;
			else{
				 s[cn++]=st[i];
				 if(st[i]=='"') flag=1;
			}
		}
		s[cn]=0;
		if(strcmp(s,"try")==0)
		{
			if(f==0)
				num++;
			else t++;
		}
		else if(s[0]=='t')
		{
			if(num==0) ff=2;
			f=1;
			for(int i=0;s[i];i++)
			{
				if(s[i]==' ') continue;
				if(s[i]=='(')
				{
					int j;
					for(j=i+1;s[j]!=')';j++)
					{
						if(s[j]==' ') continue;
						book[cnt++]=s[j];
					}
					book[cnt]=0;
					i=j-1;
				}
				//else break;
			}
		}
		else if(s[0]=='c')
		{
			char ss[1100],sss[1100],ssn=0,sssn=0;
			for(int i=0;i<strlen(s);i++)
			{
				if(s[i]==' ') continue;
				if(s[i]=='(')
				{
					int j;
					for(j=i+1;s[j]!=',';j++)
					{
						if(s[j]==' ') continue;
						ss[ssn++]=s[j];
					}
					ss[ssn]=0;
					i=j;
				}
				if(s[i]=='"')
				{
					int j;
					for(j=i+1;s[j]!='"';j++)
					{
						sss[sssn++]=s[j];
					}
					sss[sssn]=0;
					if(f&&t==0&&strcmp(ss,book)==0&&ff==0)
					{
						puts(sss);
						ff=1;
					}
				}
			}
			if(t==0) num--;
			else t--;
		}
	}
	if(ff==0||ff==2) puts("Unhandled Exception");
	return 0;
 }


#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<map>
using namespace std;
char book[1100];
int cnt=0;
int main()
{
	int n;
	scanf("%d",&n);
	getchar();
	map<string,string> ma;
	char s[1100],st[1100],cn=0;
	int f=0,num=0,t=0,ff=0;
	while(n--)
	{
		cn=0;
		gets(st);
		for(int i=0;st[i];i++)
		{
			if(st[i]==' '&&cn==0) continue;
			else{
				 s[cn++]=st[i];
			}
		}
		s[cn]=0;
		if(strcmp(s,"try")==0)
		{
			if(f==0)
				num++;
			else t++;
		}
		else if(s[0]=='t')
		{
			f=1;
			for(int i=0;s[i];i++)
			{
				if(s[i]==' ') continue;
				if(s[i]=='(')
				{
					int j;
					for(j=i+1;s[j]!=')';j++)
					{
						if(s[j]==' ') continue;
						book[cnt++]=s[j];
					}
					book[cnt]=0;
					i=j-1;
				}
				//else break;
			}
		}
		else if(s[0]=='c')
		{
			char ss[1100],sss[1100],ssn=0,sssn=0;
			for(int i=0;i<strlen(s);i++)
			{
				if(s[i]==' ') continue;
				if(s[i]=='(')
				{
					int j;
					for(j=i+1;s[j]!=',';j++)
					{
						if(s[j]==' ') continue;
						ss[ssn++]=s[j];
					}
					ss[ssn]=0;
					i=j;
				}
				if(s[i]=='"')
				{
					int j;
					for(j=i+1;s[j]!='"';j++)
					{
						sss[sssn++]=s[j];
					}
					sss[sssn]=0;
					if(f&&t==0&&strcmp(ss,book)==0&&ff==0)
					{
						puts(sss);
						ff=1;
					}
				}
			}
			if(t==0) num--;
			else t--;
		}
	}
	if(!ff) puts("Unhandled Exception");
	return 0;
 }


#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<map>
using namespace std;
char book[1100];
int cnt=0;
int main()
{
	int n;
	scanf("%d",&n);
	getchar();
	map<string,string> ma;
	char s[1100],st[1100],cn=0;
	int f=0,num=0,t=0,ff=0;
	while(n--)
	{
		cn=0;
		gets(st);
		for(int i=0;st[i];i++)
		{
			if(st[i]==' '&&cn==0) continue;
			else{
				 s[cn++]=st[i];
			}
		}
		s[cn]=0;
		if(strcmp(s,"try")==0)
		{
			if(f==0)
				num++;
			else t++;
		}
		else if(s[0]=='t')
		{
			if(num==0) ff=2;
			f=1;
			for(int i=0;s[i];i++)
			{
				if(s[i]==' ') continue;
				if(s[i]=='(')
				{
					int j;
					for(j=i+1;s[j]!=')';j++)
					{
						if(s[j]==' ') continue;
						book[cnt++]=s[j];
					}
					book[cnt]=0;
					i=j-1;
				}
				//else break;
			}
		}
		else if(s[0]=='c')
		{
			char ss[1100],sss[1100],ssn=0,sssn=0;
			for(int i=0;i<strlen(s);i++)
			{
				if(s[i]==' ') continue;
				if(s[i]=='(')
				{
					int j;
					for(j=i+1;s[j]!=',';j++)
					{
						if(s[j]==' ') continue;
						ss[ssn++]=s[j];
					}
					ss[ssn]=0;
					i=j;
				}
				if(s[i]=='"')
				{
					int j;
					for(j=i+1;s[j]!='"';j++)
					{
						sss[sssn++]=s[j];
					}
					sss[sssn]=0;
					if(f&&t==0&&strcmp(ss,book)==0&&ff==0)
					{
						puts(sss);
						ff=1;
					}
				}
			}
			if(t==0) num--;
			else t--;
		}
	}
	if(ff==0||ff==2) puts("Unhandled Exception");
	return 0;
 }


#include <bits/stdc++.h>
#define ll long long
#define ii pair<string,string>
#define oo INT_MAX
using namespace std;
const int N = 1e5+7;

ii a[N];
string ans[N];

int main()
{
    ios::sync_with_stdio(0);

    int n;
    cin >> n;
    vector<int> blocks;
    string s,s1;
    getline(cin,s);
    for (int i = 0 ; i < n ; i++)
    {
        s=s1="";
        getline(cin,s);
        //cout << s << endl;;
        bool t,c;
        int start = 0;
        t=c=0;
        for (int j = 0 ; j < s.size() ; j++)
        {
            if ((t||c) && s[j] == '(')
            {
                start = 1;
            }
            else if (start == 2 && s[j] != '"')
            {
                s1.push_back(s[j]);
            }
            else if (start == 1 && s[j] != ' ' && s[j] != ')' && s[j] != ',' && s[j] != '"')
            {
                s1.push_back(s[j]);
            }
            else if (t && s1.size() != 0)
            {
                a[i].second = s1;
                //cout <<s1 << endl;
                break;
            }
            else if (start == 1 && s[j] == '"')
            {
                a[blocks[blocks.size()-1]].second = s1;
                s1 = "";
                start = 2;
            }
            else if (start == 2 && s[j] == '"')
            {
                ans[blocks[blocks.size()-1]] = s1;
                //cout << blocks[blocks.size()-1] << endl;
                blocks.pop_back();
                break;
            }
            else if (t||c) continue;
            else if (s[j] != ' ' && s.substr(j,3) == "try")
            {
                blocks.push_back(i);
                a[i].first = "try";
                break;
            }
            else if(s[j] != ' ' && s.substr(j,5) == "throw")
            {
                a[i].first = "throw";
                t = 1;
            }
            else if (s[j] != ' ' && s.substr(j,5) == "catch")
            {
                a[i].first = "catch";
                c = 1;
            }
        }
        //cout << s1 << endl;
    }
    vector<int> vec;
    for (int i = 0 ; i < n ; i++)
    {
        if (a[i].first == "throw")
        {
            string res = "Unhandled Exception";
            for (int j = vec.size()-1;j >= 0 ; j--)
            {
                if (a[i].second == a[vec[j]].second) {res = ans[vec[j]];break;}
            }
            cout << res << endl;
            return 0;
        }
        else if (a[i].first == "try")
        {
            vec.push_back(i);
        }
        else if (a[i].first == "catch")
        {
            vec.pop_back();
        }
    }

    return 0;
}


// practice with kaiboy
import java.io.*;
import java.util.*;

public class CF195E extends PrintWriter {
	CF195E() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF195E o = new CF195E(); o.main(); o.flush();
	}

	static final int MD = 1000000007;
	int[] pp, ww;
	int find(int i) {
		int p = pp[i];
		if (p == -1)
			return i;
		pp[i] = find(p);
		ww[i] = (ww[i] + ww[p]) % MD;
		return pp[i];
	}
	void main() {
		int n = sc.nextInt();
		pp = new int[n]; Arrays.fill(pp, -1);
		ww = new int[n];
		int ans = 0;
		for (int i = 0; i < n; i++) {
			int k = sc.nextInt();
			while (k-- > 0) {
				int j = sc.nextInt() - 1;
				int x = sc.nextInt();
				int r = find(j);
				int w = (ww[j] + x) % MD;
				pp[r] = i;
				ww[r] = w;
				ans = (ans + w) % MD;
			}
		}
		println(ans);
	}
}


// practice with kaiboy
import java.io.*;
import java.util.*;

public class CF195E extends PrintWriter {
	CF195E() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF195E o = new CF195E(); o.main(); o.flush();
	}

	static final int MD = 1000000007;
	int[] pp, ww;
	int find(int i) {
		int p = pp[i];
		if (p == -1)
			return i;
		pp[i] = find(p);
		ww[i] = (ww[i] + ww[p]) % MD;
		return pp[i];
	}
	void main() {
		int n = sc.nextInt();
		pp = new int[n]; Arrays.fill(pp, -1);
		ww = new int[n];
		int ans = 0;
		for (int i = 0; i < n; i++) {
			int k = sc.nextInt();
			while (k-- > 0) {
				int j = sc.nextInt() - 1;
				int x = sc.nextInt();
				int r = find(j);
				int w = (ww[j] + x) % MD;
				pp[r] = i;
				ww[r] = w;
				ans = (ans + w) % MD;
			}
		}
		if (ans < 0)
			ans += MD;
		println(ans);
	}
}


#include<bits/stdc++.h>
#include<algorithm>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define is insert
#define rep1(i,a,b) for(long long i=a;i<=b;i++)
#define mp make_pair
#define mh make_heap
#define F first
#define S second
//#define fin cin
//#define fout cout
#define file ifstream fin("input.txt");ofstream fout("output.txt");
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fr(n) for(long long i=0;i<n;i++)
#define rep(i,a,b) for(long long i=a;i<b;i++)
#define ALL(x) (x).begin(), (x).end()
#define int long long
typedef long long ll;
#define lb lower_bound
#define ub uper_bound
#define bs lower_bound
typedef pair<ll,ll> pairs;
typedef vector<ll> vi;
typedef vector<pairs> vpair;
ll root[500000],dep[500000],ans=0;
map<pair<ll,ll>,ll>ma;
ll mod=1000000007;
ll fin(ll r)
{
    if(root[r]==r)
        return r;
    ll op=root[r];
    ll np=fin(root[r]);
    dep[r]+=(dep[op]);
    root[r]=np;
    return root[r];
}
void connect(ll child,ll par,ll wei)
{
    ll chi=child;
    ll root_child=fin(child);
    root[root_child]=par;
    ma[{par,root_child}]=(dep[chi]+wei)%mod;
    //dep[chi]=(dep[chi]+wei)%mod;
    //cout<<chi<<" "<<root_child<<" "<<"root["<<root_child<<"] :"<<par<<" "<<dep[chi]<<endl;
    dep[root_child]=(dep[chi]+wei)%mod;
    //vec[i].pb({root_child,dep[child]});
   // vec[root_child].pb({i,dep[child]});

}

void solve()
{
    ll n;cin>>n;
    fr(n+1)
        root[i]=i;
    rep(i,1,n+1)
    {
        ll k;cin>>k;
        if(k==0)
        continue;
        rep(j,0,k)
        {
            ll v,x;
            cin>>v>>x;
            connect(v,i,x);
        }
    }
    ll ans=0;
    for(auto x:ma)
    {
        //cout<<(x.second)<<endl;
        ans=(ans+(x.S)+mod)%mod;
    }
    cout<<ans<<endl;
    return ;
}
int32_t main()
{
    ll t=1;//cin>>t;
    fr(t)
    solve();
    return 0;
}


#include<bits/stdc++.h>
#include<algorithm>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define is insert
#define rep1(i,a,b) for(long long i=a;i<=b;i++)
#define mp make_pair
#define mh make_heap
#define F first
#define S second
//#define fin cin
//#define fout cout
#define file ifstream fin("input.txt");ofstream fout("output.txt");
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fr(n) for(long long i=0;i<n;i++)
#define rep(i,a,b) for(long long i=a;i<b;i++)
#define ALL(x) (x).begin(), (x).end()
#define int long long
typedef long long ll;
#define lb lower_bound
#define ub uper_bound
#define bs lower_bound
typedef pair<ll,ll> pairs;
typedef vector<ll> vi;
typedef vector<pairs> vpair;
ll root[500000],dep[500000],ans=0;
map<pair<ll,ll>,ll>ma;
ll mod=1000000007;
ll fin(ll r)
{
    if(root[r]==r)
        return r;
    ll op=root[r];
    ll np=fin(root[r]);
    dep[r]+=(dep[op]);
    root[r]=np;
    return root[r];
}
void connect(ll child,ll par,ll wei)
{
    ll chi=child;
    ll root_child=fin(child);
    root[root_child]=par;
    ma[{par,root_child}]=(dep[chi]+wei)%mod;
    //dep[chi]=(dep[chi]+wei)%mod;
    //cout<<chi<<" "<<root_child<<" "<<"root["<<root_child<<"] :"<<par<<" "<<dep[chi]<<endl;
    dep[root_child]=(dep[chi]+wei)%mod;
    //vec[i].pb({root_child,dep[child]});
   // vec[root_child].pb({i,dep[child]});

}

void solve()
{
    ll n;cin>>n;
    fr(n+1)
        root[i]=i;
    rep(i,1,n+1)
    {
        ll k;cin>>k;
        if(k==0)
        continue;
        rep(j,0,k)
        {
            ll v,x;
            cin>>v>>x;
            connect(v,i,x);
        }
    }
    ll ans=0;
    for(auto x:ma)
    {
        //cout<<(x.second)<<endl;
        ans=(ans+(x.S))%mod;
    }
    cout<<ans<<endl;
    return ;
}
int32_t main()
{
    ll t=1;//cin>>t;
    fr(t)
    solve();
    return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define fast ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define f first
#define s second
#define int long long
#define sz(x) (ll)(x.size())
using namespace std;

const int mod = 1e9+7;

int expo_pow(int x,int y){
 if(y == 0) return 1;
  y=y%(mod-1);
  x%=mod;
  if(y==0) y=mod-1;
  int res=1;
  while(y){
    if(y&1) res=(res*x)%mod;
    x=(x*x)%mod;
    y>>=1;
  }
  return res;
}

ll add()
{
    return 0;
}

template <typename T, typename... Types>
T add(T var1, Types... var2){
    return (((((ll)(var1)) % mod + (ll)(add(var2...))) % mod) + mod) % mod;
}

ll mul(){
    return 1;
}

template <typename T, typename... Types>
T mul(T var1, Types... var2){
    return (((ll)(var1)) % mod * (ll)(mul(var2...))) % mod;
}

const int mx = 1e5+2;

int n;
pair<int,int> par[mx];
int dep[mx];
int sz[mx];

pii find_bap(int x){
  if(x!=par[x].f){
    int len = par[x].s;
    len%=mod;
    par[x] = find_bap(par[x].f);
    par[x].s += len;
    par[x].s += mod;
    par[x].s %= mod;
  }
  return par[x];
}

void solve(){
  cin>>n;
  for(int i=0;i<=n;i++) par[i] = {i,0};
  int ans = 0;
  for(int i=0;i<n;i++){
    int k;
    cin>>k;
    for(int j=0;j<k;j++){
      int root,we;
      cin>>root>>we;
      auto bap = find_bap(root);
      int total_we = bap.s + we;
      total_we += mod;
      total_we %=mod;
      par[bap.f] = {i+1,total_we};
      ans += total_we;
      ans += mod;
      ans %= mod;
    }
  }

  cout<<ans<<"\n";
}

signed main(){
  fast;
  int test = 1;
  int i=1;
  while(test--){
    solve();
  }
}


//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC opatimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#pragma GCC diagnostic ignored "-Wmissing-declarations"
#define FINAL_OUT(x) {cout << (x) << '\n'; exit(0); }

int const maxn = 100005;
int par[maxn];
int sum[maxn];

int const mod = 1e9+7;

inline void safe_add(int& x, const int y) {
    x += y;
    if( x >= mod)
        x -= mod;
}

inline int fnd(const int x) {
    if (par[x] == x)
        return x;
    int p = fnd(par[x]);
    safe_add(sum[x], sum[par[x]]);
    par[x] = p;
    return p;
}

int main() {
//    freopen("in.txt","r", stdin);
//    freopen("out.txt","w", stdout);
    cout << fixed << setprecision(15);
    ios_base::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    iota(begin(par), end(par), 0);

    int n;
    cin >> n;

    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        int k;
        cin >> k;
        while (k--) {
            int v,x;
            cin >> v >> x;
            while (x < 0)
                x += mod;
            while (x >= mod)
                x -= mod;
            int pv = fnd(v);
            int cur = sum[v];
            safe_add(cur, x);
            safe_add(ans, cur);
            safe_add(sum[pv], cur);
            par[pv] = i;
        }
    }
    cout << ans << endl;
}


/*{{{*/
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define FORS(I, S) for (int I = 0; S[I]; ++I)
#define RS(X) scanf("%s", (X))
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
#define CASET int ___T; scanf("%d", &___T); for(int cs=1;cs<=___T;cs++)
#define MP make_pair
#define PB emplace_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define F first
#define S second
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector<LL> VL;
typedef vector<PII> VPII;
typedef pair<LL,LL> PLL;
typedef vector<PLL> VPLL;
template<class T> void _R(T &x) { cin >> x; }
void _R(int &x) { scanf("%d", &x); }
void _R(int64_t &x) { scanf("%lld", &x); }
void _R(double &x) { scanf("%lf", &x); }
void _R(char &x) { scanf(" %c", &x); }
void _R(char *x) { scanf("%s", x); }
void R() {}
template<class T, class... U> void R(T &head, U &... tail) { _R(head); R(tail...); }
template<class T> void _W(const T &x) { cout << x; }
void _W(const int &x) { printf("%d", x); }
void _W(const int64_t &x) { printf("%lld", x); }
void _W(const double &x) { printf("%.16f", x); }
void _W(const char &x) { putchar(x); }
void _W(const char *x) { printf("%s", x); }
template<class T,class U> void _W(const pair<T,U> &x) {_W(x.F); putchar(' '); _W(x.S);}
template<class T> void _W(const vector<T> &x) { for (auto i = x.begin(); i != x.end(); _W(*i++)) if (i != x.cbegin()) putchar(' '); }
void W() {}
template<class T, class... U> void W(const T &head, const U &... tail) { _W(head); putchar(sizeof...(tail) ? ' ' : '\n'); W(tail...); }
#ifdef HOME
 #define DEBUG(...) {printf("# ");printf(__VA_ARGS__);puts("");}
#else
 #define DEBUG(...)
#endif
int MOD = 1e9+7;
void ADD(LL& x,LL v){x=(x+v)%MOD;if(x<0)x+=MOD;}
/*}}}*/
const int SIZE = 1e6+10;
int to[SIZE];
struct Union_Find{
    int d[SIZE];
    LL dis[SIZE];
    void init(int n){
        REP(i,n)d[i]=i,dis[i]=0;
    }
    bool is_root(int x){return d[x]==x;}
    int find(int x){
        if(x==d[x])return x;
        int y=d[x];
        d[x]=find(y);
        ADD(dis[x],dis[y]);
        return d[x];
    }
    LL get_dis(int x){
        find(x);
        return dis[x];
    }
    bool uu(int x,int y,LL v){
        x=find(x);
        y=find(y);
        if(x==y)return 0;
        ADD(dis[x],v);
        d[x]=y;
        return 1;
    }
}U;
VI e[SIZE];
int main(){
    int n;
    R(n);
    U.init(n);
    MS1(to);
    REP(i,n){
        int k;
        R(k);
        REP(j,k){
            int v;
            LL x;
            R(v,x);
            v--;
            ADD(x,U.get_dis(v));
            to[U.find(v)]=i;
            U.uu(U.find(v),i,x);
        }
    }
    LL an=0;
    REP(i,n){
        if(to[i]!=-1){
            U.find(i);
            U.find(to[i]);
            ADD(an,U.dis[i]-U.dis[to[i]]);
        }
    }
    W(an);
    return 0;
}


#pragma warning(disable:4996)
#pragma comment(linker, "/STACK:336777216")
#pragma GCC optimize("Ofast")

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>

using namespace std;
using namespace __gnu_pbds;

typedef long long ll;
#define int long long int
typedef complex<long double> cd;
const long double pi=acos(-1);
typedef double db;
typedef long double ldb;
typedef pair <int,int> pii;
typedef pair <db,db> pdd;
typedef vector<int> vi;
typedef vector<vector<int> > matrix;

#define m1 make_pair
#define pb push_back
#define flush fflush(stdout)
#define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);
#define reset(x,v) memset(x,v,sizeof(x))

#define fi first
#define se second
#define endl "\n"
#define debug(x) (cerr << #x << ": " << x << "\n")
#define setbits(x) __builtin_popcount(x)
#define setbitsll(x) __builtin_popcountll(x)
#define all(x) x.begin(),x.end()
#define pii pair<int,int>

inline int gcd(int a,int b){if(a==0) return b;return gcd(b%a,a);}
inline int power(ll a,ll n,ll m){if(n==0)return 1;ll p=power(a,n/2,m);p=(p%m*p%m)%m;if(n%2) return (p%m*a%m)%m;else return p;}
const double EPS = 1e-9;
const ll MOD =998244353;
const ll hell=1000000007;
const int INF = 1e18;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
template<typename T>
using ordered_set=tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>;

auto seed = chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 rng(seed);

double startTime;
double getCurrentTime() {
    return ((double)clock() - startTime) / CLOCKS_PER_SEC;
}
const int dx[] = { -1, 0, 1, 0 };
const int dy[] = { 0, 1, 0, -1 };

const int N=200005;
int parent[N+1];int depth[N+1];
int find(int i)
{
    if(parent[i]==i)
        return i;
    int p=find(parent[i]);
    depth[i]+=depth[parent[i]];
    return parent[i]=p;
}
void Union(int i,int j,int w)
{
    parent[j]=i;
    depth[j]+=w;
}

void solve()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        parent[i]=i;
    }
    int k,u,w;
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        cin>>k;
        for(int j=0;j<k;j++)
        {
            cin>>u>>w;
            int x=find(u);
            ans+=(w+depth[u]);
            //cout<<depth[u]<<endl;
            ans%=hell;
            Union(i,x,w+depth[u]);
        }
    }
    cout<<ans<<endl;

}

int32_t main()
{

    IOS;

    int t;
    t=1;
    //cin>>t;
    while(t--)
    {

        solve();
    }

    return 0;
}


#pragma warning(disable:4996)
#pragma comment(linker, "/STACK:336777216")
#pragma GCC optimize("Ofast")

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>

using namespace std;
using namespace __gnu_pbds;

typedef long long ll;
#define int long long int
typedef complex<long double> cd;
const long double pi=acos(-1);
typedef double db;
typedef long double ldb;
typedef pair <int,int> pii;
typedef pair <db,db> pdd;
typedef vector<int> vi;
typedef vector<vector<int> > matrix;

#define m1 make_pair
#define pb push_back
#define flush fflush(stdout)
#define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);
#define reset(x,v) memset(x,v,sizeof(x))

#define fi first
#define se second
#define endl "\n"
#define debug(x) (cerr << #x << ": " << x << "\n")
#define setbits(x) __builtin_popcount(x)
#define setbitsll(x) __builtin_popcountll(x)
#define all(x) x.begin(),x.end()
#define pii pair<int,int>

inline int gcd(int a,int b){if(a==0) return b;return gcd(b%a,a);}
inline int power(ll a,ll n,ll m){if(n==0)return 1;ll p=power(a,n/2,m);p=(p%m*p%m)%m;if(n%2) return (p%m*a%m)%m;else return p;}
const double EPS = 1e-9;
const ll MOD =998244353;
const ll hell=1000000007;
const int INF = 1e18;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
template<typename T>
using ordered_set=tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>;

auto seed = chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 rng(seed);

double startTime;
double getCurrentTime() {
    return ((double)clock() - startTime) / CLOCKS_PER_SEC;
}
const int dx[] = { -1, 0, 1, 0 };
const int dy[] = { 0, 1, 0, -1 };

const int N=200005;
int parent[N+1];int depth[N+1];
int find(int i)
{
    if(parent[i]==i)
        return i;
    int p=find(parent[i]);
    depth[i]=(depth[i]+depth[parent[i]])%hell;
    return parent[i]=p;
}
void Union(int i,int j,int w)
{
    parent[j]=i;
    depth[j]=w;
}

void solve()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        parent[i]=i;
    }
    int k,u,w;
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        cin>>k;
        for(int j=0;j<k;j++)
        {
            cin>>u>>w;
            int x=find(u);
            w=(hell+w)%hell;
            ans+=(w+depth[u]);
            ans%=hell;
            Union(i,x,(w+depth[u])%hell);
        }
    }
    cout<<ans<<endl;

}

int32_t main()
{

    IOS;

    int t;
    t=1;
    //cin>>t;
    while(t--)
    {

        solve();
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ii pair <int, int>
#define app push_back
#define all(a) a.begin(), a.end()
#define bp __builtin_popcount
#define ll long long
#define mp make_pair
#define f first
#define s second
#define Time (double)clock()/CLOCKS_PER_SEC
const int N = 1e5 + 7, MOD = 1000 * 1000 * 1000 + 7;
int par[N], d[N];

int mod(int n) {
    n %= MOD;
    if (n < 0)
        return n + MOD;
    else
        return n;
}

int root(int u) {
    if (par[u] == u) {
        return u;
    }
    else {
        int mem = par[u];
        par[u] = root(par[u]);
        d[u] = mod(d[u] + d[mem]);
        return par[u];
    }
}

signed main() {
    #ifdef HOME
    freopen("input.txt", "r", stdin);
    #else
    #define endl '\n'
    ios_base::sync_with_stdio(0); cin.tie(0);
    #endif
    for (int i = 0; i < N; ++i)
        par[i] = i;
    int n;
    cin >> n;
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        int k;
        cin >> k;
        for (int j = 0; j < k; ++j) {
            int v, x;
            cin >> v >> x;
            int r = root(v);
            par[r] = i;
            d[r] = mod(d[v] + x);
            ans = mod(ans + d[r]);
        }
    }
    cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ii pair <int, int>
#define app push_back
#define all(a) a.begin(), a.end()
#define bp __builtin_popcount
#define ll long long
#define mp make_pair
#define f first
#define s second
#define Time (double)clock()/CLOCKS_PER_SEC
const int N = 1e5 + 7, MOD = 1000 * 1000 * 1000 + 7;
int par[N], d[N], cnt[N];

int root(int u) {
    if (par[u] == u) {
        return u;
    }
    else {
        int mem = par[u];
        par[u] = root(par[u]);
        d[u] += d[mem];
        return par[u];
    }
}
int depth(int u) {
    return d[u];
}

signed main() {
    #ifdef HOME
    freopen("input.txt", "r", stdin);
    #else
    #define endl '\n'
    ios_base::sync_with_stdio(0); cin.tie(0);
    #endif
    for (int i = 0; i < N; ++i) {
        par[i] = i;
        cnt[i] = 1;
    }
    int n;
    cin >> n;
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        int k;
        cin >> k;
        for (int j = 0; j < k; ++j) {
            int v, x;
            cin >> v >> x;
            int r = root(v), dd = depth(v);

            //cout << "root " << v << " : " << r << endl;

            par[r] = i;
            cnt[i] += cnt[r];

            d[r] = (dd + x) % MOD;
            ans = (ans + d[r]) % MOD;
            //cout << r << ' ' << d[r] << endl;
        }
        //cout << "i " << i << ' ' << ans << endl;
    }
    cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ii pair <int, int>
#define app push_back
#define all(a) a.begin(), a.end()
#define bp __builtin_popcount
#define ll long long
#define mp make_pair
#define f first
#define s second
#define Time (double)clock()/CLOCKS_PER_SEC
const int N = 1e5 + 7, MOD = 1000 * 1000 * 1000 + 7;
int par[N], d[N], cnt[N];

int mod(int n) {
    n %= MOD;
    if (n < 0)
        return n + MOD;
    else
        return n;
}

int root(int u) {
    if (par[u] == u) {
        return u;
    }
    else {
        int mem = par[u];
        par[u] = root(par[u]);
        d[u] = mod(d[u] + d[mem]);
        return par[u];
    }
}

signed main() {
    #ifdef HOME
    freopen("input.txt", "r", stdin);
    #else
    #define endl '\n'
    ios_base::sync_with_stdio(0); cin.tie(0);
    #endif
    for (int i = 0; i < N; ++i) {
        par[i] = i;
        cnt[i] = 1;
    }
    int n;
    cin >> n;
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        int k;
        cin >> k;
        for (int j = 0; j < k; ++j) {
            int v, x;
            cin >> v >> x;
            int r = root(v);
            par[r] = i;
            cnt[i] += cnt[r];
            d[r] = mod(d[v] + x);
            ans = mod(ans + d[r]);
        }
    }
    cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ii pair <int, int>
#define app push_back
#define all(a) a.begin(), a.end()
#define bp __builtin_popcount
#define ll long long
#define mp make_pair
#define f first
#define s second
#define Time (double)clock()/CLOCKS_PER_SEC
const int N = 1e5 + 7, MOD = 1000 * 1000 * 1000 + 7;
int par[N], d[N], cnt[N];

int root(int u) {
    if (par[u] == u) {
        return u;
    }
    else {
        d[u] += d[par[u]];
        par[u] = root(par[u]);
    }
}
int depth(int u) {
    return d[u];
}

signed main() {
    #ifdef HOME
    freopen("input.txt", "r", stdin);
    #else
    #define endl '\n'
    ios_base::sync_with_stdio(0); cin.tie(0);
    #endif
    for (int i = 0; i < N; ++i) {
        par[i] = i;
        cnt[i] = 1;
    }
    int n;
    cin >> n;
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        int k;
        cin >> k;
        for (int j = 0; j < k; ++j) {
            int v, x;
            cin >> v >> x;
            int r = root(v), dd = depth(v);
            par[r] = i;
            cnt[i] += cnt[r];

            d[r] = (dd + x) % MOD;
            ans = (ans + d[r]) % MOD;
            //cout << cnt[r] << ' ' << d[r] << endl;
        }
        //cout << "i " << i << ' ' << ans << endl;
    }
    cout << ans << endl;
}


///supercalifragilisticexpialidocious.
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cassert>
#include <cstdlib>
#include <cctype>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <numeric>
#include <utility>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <set>
#include <list>
#include <bitset>
#include <complex>
using namespace std;
#define f first
#define s second
#define PB pop_back
#define pb push_back
#define mp make_pair
#define int long long
#define sz(s) (int)s.size()
#define seper(n) setprecision(n)
#define all(v) v.begin(),v.end()
#define mem(a,b) memset(a,b,sizeof a)
#define IOS ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
typedef long long ll;
typedef map<int , int> mii;
typedef pair<int , int> pii;
typedef map<string , int> msi;
typedef pair<int , string> pis;
typedef pair<int , pair<int , int> > piii;
const int MAXN = 1e5 + 10 , MOD = 1e9 + 7;
int n , k , v , x , ans , prnt , par[MAXN] , dep[MAXN];
int Find(int u)
{
	if(u == par[u])
		return u;
	dep[u] = (dep[par[u]] + dep[u]) % MOD;
	return par[u] = Find(par[u]);
}
int32_t main()
{
	cin >> n;
	for(int i = 0 ; i <= n ; i ++)
		par[i] = i , dep[i] = 0;
	for(int i = 0 ; i < n ; i ++)
	{
		cin >> k;
		for(int j = 0 ; j < k ; j ++)
			cin >> v >> x , v -- , prnt = Find(v) , ans = (ans + dep[v] + x + MOD) % MOD , par[prnt] = i , dep[prnt] = (dep[v] + x) % MOD;
	}
	/*for(int i = 0 ; i < n ; i ++)
		cout << dep[i] << " ";
	cout << '\n';*/
	return cout << (ans + MOD) % MOD << '\n' , 0;
}


///supercalifragilisticexpialidocious.
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cassert>
#include <cstdlib>
#include <cctype>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <numeric>
#include <utility>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <set>
#include <list>
#include <bitset>
#include <complex>
using namespace std;
#define f first
#define s second
#define PB pop_back
#define pb push_back
#define mp make_pair
#define int long long
#define sz(s) (int)s.size()
#define seper(n) setprecision(n)
#define all(v) v.begin(),v.end()
#define mem(a,b) memset(a,b,sizeof a)
#define IOS ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
typedef long long ll;
typedef map<int , int> mii;
typedef pair<int , int> pii;
typedef map<string , int> msi;
typedef pair<int , string> pis;
typedef pair<int , pair<int , int> > piii;
const int MAXN = 1e5 + 10 , MOD = 1e9 + 7;
int n , k , v , x , ans , prnt , par[MAXN] , dep[MAXN];
int Find(int u)
{
	if(u == par[u])
		return u;
	dep[u] = (dep[par[u]] + dep[u]) % MOD;
	return par[u] = Find(par[u]);
}
int32_t main()
{
	cin >> n;
	for(int i = 0 ; i <= n ; i ++)
		par[i] = i , dep[i] = 0;
	for(int i = 0 ; i < n ; i ++)
	{
		cin >> k;
		for(int j = 0 ; j < k ; j ++)
			cin >> v >> x , v -- , prnt = Find(v) , ans = (ans + dep[v] + x + MOD) % MOD , par[prnt] = i , dep[prnt] = (dep[v] + x) % MOD;
	}
	for(int i = 0 ; i < n - 1 ; i ++)
		cout << dep[i] << " ";
	cout << '\n';
	return cout << (ans + MOD) % MOD << '\n' , 0;
}